【问题标题】:Parsing JSON returned via an AJAX POST formating issue解析通过 AJAX POST 格式问题返回的 JSON
【发布时间】:2013-11-22 07:06:21
【问题描述】:

我有一个 php 返回一些 json 以响应通过 ajax 函数发出的 POST 请求。
在我的 php 函数中,我像这样格式化数据:

//json return
$return["answers"] = json_encode($result);
echo json_encode($return);

这将返回以下字符串:

answers: "[{"aa":"Purple","0":"Purple","ab":"Blue","1":"Blue","ac":"Red","2":"Red","ad":"Yellow","3":"Yellow"}]" 

这就是我试图抓住它以使用数据的地方:

$.ajax({
            type: "POST",
            url: "http://ldsmatch.com/pieces/functions/question.functions.php",
            dataType : 'JSON',
            data: dataString,
            success: function(data) {
                alert(data.answers[0]["aa"]);
            }       
        });

我一直在尝试仅提醒数据,以便在设置所需的变量之前对其进行可视化,但在正确格式化它以使其可用时遇到了一些问题。

如果我提醒data.answers[0],那么它只会显示字符串中的第一个字符,即括号 [,如果我随后更改数字,它将遍历返回字符串中的每个字符。

我尝试过其他变体,例如:

data.answers[0]["aa"]   (this returns 'undefined' in the alert)
data.answers["aa"]      (this returns 'undefined' in the alert)
data.answers[0]         (this returns the first character of the string)

我觉得我很接近,但错过了一些东西。任何指导表示赞赏。

编辑:

感谢所有建议。我删除了第二个 json_encode 并能够使用 data.answers[0].aa 进行解析

【问题讨论】:

  • @palaѕн 刚刚做了,它返回未定义。还尝试了返回 Cannot read property '0' of undefined 欢呼的 data.answers.aa[0]。
  • console.log(data) 得到什么?请在此处发布...
  • 你可以使用 alert(JSON.stringify(data));
  • 只要把这一行放到成功函数console.log(data)中;并检查萤火虫它会帮助你更多。
  • @SohilDesai 似乎只记录了我已经知道存在并格式化的字符串:Object {answers: "[{"aa":"Purple","0":"Purple","ab":"Blue","1":"Blue…"ac":"Red","2":"Red","ad":"Yellow","3":"Yellow"}]"}

标签: javascript php jquery ajax json


【解决方案1】:

成功:函数(数据){ var json = $.parseJSON(data); 警报(json.answers[0][“aa”]); }

【讨论】:

  • 这基本上是有效的,但我也删除了第二个 json_encode 并且能够使用 data.answers[0].aa 获得结果,而无需在 js 中进行解析。
【解决方案2】:

像这样使用 parseJson

var json = $.parseJSON(data);
$(json).each(function(i,val){
    $.each(val,function(k,v){
      console.log(k+" : "+ v);     
    });
});

【讨论】:

  • 控制台返回:Uncaught SyntaxError: Unexpected token o jquery.js:550 x.extend.parseJSON jquery.js:550 $.ajax.success subpage.questions.js:105 c jquery.js:3074 p.fireWith jquery.js:3186 k jquery.js:8253 r
【解决方案3】:

如果您在 PHP 端移除双重编码会怎样?您有一个带有 JSON 字符串的对象,而不是第一个属性是对象本身的对象,或者您可以按照上面的建议在客户端显式解码“answers”属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-06
    • 2017-12-05
    • 2015-11-01
    • 1970-01-01
    • 2018-06-28
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多