简体   繁体   English

在AJAX中使用PHP返回的Json

[英]Using Json returned by PHP in AJAX

My PHP script is returning a JSON object that I am receiving in AJAX call. 我的PHP脚本返回了我在AJAX调用中收到的JSON对象。

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

Now in my AJAX call , I try to get the value but all I get is "/" or "'" . 现在,在我的AJAX调用中,我尝试获取值,但是得到的只是"/""'"

I am doing this in 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

Am I doing something wrong here? 我在这里做错什么了吗?

I have seen this on SO 我已经看到了

I think the JSON.parse solve your problem. 我认为JSON.parse解决了您的问题。

The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing. JSON.parse()方法将字符串解析为JSON,可以选择转换解析产生的值。

Examples 例子

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

Using the reviver parameter 使用齐磊参数

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.
});

Ref: 参考:

JSON.parse() JSON.parse()

JSON Example - Object From String JSON示例-字符串中的对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM