2016-01-23 47 views
0

我的PHP脚本正在返回我在AJAX调用中收到的JSON对象。在AJAX中使用由PHP返回的Json

$arr[0] = $resp; 
      $arr[1] = $e; 
      return json_encode($arr); 

现在在我的AJAX调用,我试图让价值,但我得到的是"/""'"

我正在做这个AJAX。

dd = JSON.stringify(x.responseText); //this is the response from PHP which is correct I have verified. 
alert(dd[0]); //supposed to output $arr[0] but it doesn't 

我在这里做错了什么?

I have seen this on SO

+0

'console.log(dd)' –

+0

@u_mulder问题不在于alert或console.log或打印问题,它关于获取正确的数据。 –

+1

Console.log,看看你在dd中有什么。 'JSON.stringify'顺便说一句json字符串。也许你需要'JSON.parse'? –

回答

0

我觉得JSON.parse解决您的问题。

JSON.parse()方法将字符串解析为JSON,可以选择使用 来转换解析产生的值。

实例

JSON.parse('{}');    // {} 
JSON.parse('true');   // true 
JSON.parse('"foo"');   // "foo" 
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"] 
JSON.parse('null');   // null 

使用齐磊参数

JSON.parse('{"p": 5}', function(k, v) { 
    if (k === '') { return v; } // if topmost value, return it, 
    return v * 2;    // else return v * 2. 
});       // { p: 10 } 

JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', function(k, v) { 
    console.log(k); // log the current property name, the last is "". 
    return v;  // return the unchanged property value. 
}); 

价:

JSON.parse()

JSON Example - Object From String