Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/421.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 解析通过AJAX后期格式化问题返回的JSON_Javascript_Php_Jquery_Ajax_Json - Fatal编程技术网

Javascript 解析通过AJAX后期格式化问题返回的JSON

Javascript 解析通过AJAX后期格式化问题返回的JSON,javascript,php,jquery,ajax,json,Javascript,Php,Jquery,Ajax,Json,我有一个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"

我有一个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_编码,能够用
数据进行解析。答案[0]。aa

像这样使用parseJson

var json = $.parseJSON(data);
$(json).each(function(i,val){
    $.each(val,function(k,v){
      console.log(k+" : "+ v);     
    });
});
成功:功能(数据){ var json=$.parseJSON(数据); 警报(json.answers[0][“aa”]);
}

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

@palaѕѕѕѕѕѕѕѕѕѕѕ刚做了,它返回了未定义的内容。还尝试了data返回的
无法读取未定义的
cheers的属性“0”。您从
控制台.log(数据)
中得到了什么?请在此处发布…您可以使用警报(JSON.stringify(数据));只需将此行放入success函数console.log(数据)中即可;并检查firebug,它将对您有更多帮助。@SohilDesai,它似乎只是记录字符串,我已经知道该字符串存在并已格式化:
Object{answers:[{“aa”:“Purple”,“0”:“Purple”,“ab”:“Blue”,“1”:“Blue…”“ac”:“Red”,“2”:“Red”,“ad”:“Yellow”,“3”:“Yellow”}]“}”
Console返回:
Uncaught SyntaxError:o jquery.js:550 x.extend.parseJSON jquery.js:550$.ajax.success子页面.questions.js:105 c jquery.js:3074 p.fireWith jquery.js:3186 k jquery.js:8253 r意外标记
这基本上是有效的,但我还删除了第二个json_编码,并能够使用数据获得结果。答案[0].aa,而不在js中进行解析。