【问题标题】:Using Json returned by PHP in AJAX在 AJAX 中使用 PHP 返回的 Json
【发布时间】:2016-01-23 13:15:07
【问题描述】:

我的 PHP 脚本返回一个我在 AJAX 调用中接收到的 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

【问题讨论】:

  • @u_mulder 问题不在于警报、console.log 或打印,而在于获取正确的数据。
  • Console.log 并查看您在 dd 中的内容。 JSON.stringify btw 从它的参数中生成 json 字符串。也许你需要JSON.parse
  • @u_mulder 是 JSON.parse 工作 :) 谢谢

标签: javascript php jquery json ajax


【解决方案1】:

我认为 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

使用 reviver 参数

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-24
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 2021-11-24
    相关资源
    最近更新 更多