使用jQuery从PHP读取JSON数据

使用jQuery从PHP读取JSON数据,php,jquery,arrays,json,Php,Jquery,Arrays,Json,我使用json\u encode从PHP发送了一个数组,并尝试使用AJAX和jQuery获取该数组。 一切都好 JSON结构是: names{"p1":"John","p5":"Smith"} jQuery代码是: $.ajax({ type: "POST", url: "return.php", dataType: "json", data: "id=56", success: function(data) { $(data.names).each(function(key,

我使用
json\u encode
从PHP发送了一个数组,并尝试使用AJAX和jQuery获取该数组。 一切都好

JSON结构是:

names{"p1":"John","p5":"Smith"}
jQuery代码是:

$.ajax({
type: "POST",
url: "return.php",
dataType: "json",
data: "id=56",
success: function(data) {
        $(data.names).each(function(key, txt) {
            alert(txt);
        });
    }
}
这个代码不返回任何东西!我认为浏览器不会在
中输入每个

我该怎么办?

改为:

$(data.names).each(function(key, txt) {
    alert(txt);
});
使用以下命令:

$.each(data.names, function(key, txt) {
    alert(txt);
});
正如您所提到的,您的json似乎不正确:
名称{“p1”:“John”,“p5”:“Smith”}

这应该是这样的:

{
    "names": {
        "p1": "John",
        "p5": "Smith"
    }
}
您可以在此处检查json:

而不是以下内容:

$(data.names).each(function(key, txt) {
    alert(txt);
});
使用以下命令:

$.each(data.names, function(key, txt) {
    alert(txt);
});
正如您所提到的,您的json似乎不正确:
名称{“p1”:“John”,“p5”:“Smith”}

这应该是这样的:

{
    "names": {
        "p1": "John",
        "p5": "Smith"
    }
}

您可以在这里检查json:

我建议您使用jQuery的$.getJSON(); 而是直接回答你的问题;您没有关闭ajax()函数

$.ajax({
type: "POST",
url: "return.php",
dataType: "json",
data: "id=56",
success: function(data) {
        $(data.names).each(function(key, txt) {
            alert(txt);
        });
    }
});

我建议您使用jQuery的$.getJSON(); 而是直接回答你的问题;您没有关闭ajax()函数

$.ajax({
type: "POST",
url: "return.php",
dataType: "json",
data: "id=56",
success: function(data) {
        $(data.names).each(function(key, txt) {
            alert(txt);
        });
    }
});

在代码中,您可以只使用parseJSON()

$.ajax({ 类型:“POST”, url:“return.php”, 数据类型:“json”, 数据:“id=56”, 成功:功能(数据){ var d=jQuery.parseJSON(数据); //…做事 } });
在代码中,您可以只使用parseJSON()

$.ajax({ 类型:“POST”, url:“return.php”, 数据类型:“json”, 数据:“id=56”, 成功:功能(数据){ var d=jQuery.parseJSON(数据); //…做事 } });