为什么我的AJAX json对象不被javascript理解,即使使用';json';数据类型?
我的js代码只是从我的服务器获取一个json对象,但我认为应该自动解析它并将其转换为具有属性的对象,但它不允许正确访问为什么我的AJAX json对象不被javascript理解,即使使用';json';数据类型?,ajax,json,drupal,Ajax,Json,Drupal,我的js代码只是从我的服务器获取一个json对象,但我认为应该自动解析它并将其转换为具有属性的对象,但它不允许正确访问 $.ajax({ type: 'POST', url: '/misc/json-sample.js', data: {href: path}, // THIS IS THE POST DATA THAT IS PASSED IN; safe2ignore. dataType: 'json', success:
$.ajax({
type: 'POST',
url: '/misc/json-sample.js',
data: {href: path}, // THIS IS THE POST DATA THAT IS PASSED IN; safe2ignore.
dataType: 'json',
success: function (datax) {
if (datax.debug) {
alert('Debug data: ' + datax.debug);
} else {
alert('No debug data: ' + datax.toSource() ) ;
}
/misc/json-sample.js文件是:[{“path”:“examplemodule/parent1/child1/grand1”,“title”:“First-grander选项”,“debug”:“First-grander选项”,“children”:false}]
(我还尝试从drupal返回该对象,如下所示,结果相同。)
misc/json-sample.js的Drupal版本:
$items[] = array(
'path' => 'examplemodule/parent1/child1/grandchild1',
'title' => t('First grandchild option'),
'debug' => t('debug me!'),
'children' => FALSE
);
print drupal_to_js($items);
(在具有toSource()功能的FF中)发生的是带有“无调试数据:[{path:“examplemodule/parent1/child1/grand1”,title:“First-grander option”,debug:“First-grander option”,childs:false}]的警报
谢谢您需要将内容类型标题设置为application/json
header("Content-Type: application/json");
print drupal_to_js($items);
我很困惑,您希望debug字段在Drupal返回的对象中,但在
/misc/json sample.js
中没有这个字段?如果您将该字段添加到硬编码的js文件中是否有效?对不起,我错误地发布了错误版本的json-sample.js文件和警报输出。我修好了,谢谢。我在drupal版本中测试了Michael推荐的更改。这个指令现在似乎是标题的一部分,因为当我直接从localhost加载URL为/ra/js时,FF会问我“FF应该如何处理这个应用程序/json”——但jquery应用程序仍然没有正确解析结果,并调用了相同的警报。我想我已经得到了。[{“path”:“examplemodule/parent1/child1/grand1”,“title”:“First-grander-option”,“debug”:“First-grander-option”,“children:false}]是一个对象数组!如果没有[],则正确解析.js伪文件。因此,我可能引用了错误的.debug,因为它不是列表中的元素,而是列表中第一项的元素。