我在解析我认为从 ajax 调用返回的格式良好的 json 时遇到了奇怪的问题(使用 jQuery 1.4.4)。奇怪的是,在我的开发服务器上它工作正常但在线失败。
ajax调用返回的数据如下:
returnData = { "status": true, "data": { "error_return": false, "error_index": -1, "message_display": { "main_message": "hello", "name": "tommy tune the man", "mailed_to": "t@t.com", "subject": "I tried this", "subject_message": "you have a technical question or comment.", "test_me": "you have a technical question or comment." } } };
jsLint 和 jsonLint 都验证这个结构。
当我尝试访问 returnData.data 时发生错误
在“失败”的情况下,我从 jQuery.ajax 选项中删除了 dataType,从而允许“最佳猜测”功能。如果我指定 json,jQuery 会抛出一个解析错误,声称 json 无效。我尝试了各种各样的东西(包括可怕的 eval() 和 jquery-2json 插件,但没有运气。即使是 jQ 实用程序 jQuery.parseJSON 也失败了。
该问题出现在 FF 3.6.13 和最新的 Safari / Chrome 中。
问题 1:有谁知道最新的 jQuery 对此会抛出解析错误吗?
问题2:当我尝试以下操作时,我成功了:
- var 成功 = returnData.status;
但是以下是未定义的:
- var errorReturn = returnData.data.error_return。
奇怪的是,如果我将对象“粘贴”到控制台中,Firebug 会将其视为一个对象,但在脚本中 1)在 console.dir 中返回“无子对象” 2)但会在 console.log 中显示该对象。
非常感谢的想法
更新:我发现服务器设置的内容类型不正确。在格式化 JSON 以返回的服务器端 PHP 中(在这种情况下在 Drupal 6 中创建(我不得不破解核心可选包括“commons.inc”),我用“应用程序/json”替换了内容类型。这个现在可以工作了。这个问题已经在 Drupal 7 中得到纠正。