如何访问从JQuery接收的JSON响应中的数据

How to access data in JSON response recieved from JQuery?

本文关键字:JSON 响应 数据 JQuery 何访问 访问      更新时间:2023-09-26

如何访问在JQuery AJAX请求的完整函数中返回的JSON中存储的数据?例如,我有以下代码:

$.ajax({
    url: 'buildings.php',
    data: "building=" + building,
    complete: function (response) {
        alert(response.responseText);
        alert(response.name);
    }
});

在第一个警报中,它显示以下内容,这是我从PHP发送的预期JSON数据。

{"name":"HSB","description":"description","directionsURL":"directionsURL","imageArray":{"1":"URL 1","2":"URL 2"}}
在第二个警报中,它显示
undefined

如何访问第一个警报中显示的收到的数据?

如果您将dataType: "json"添加到调用中,则响应将成为json对象:

$.ajax({
    url: 'buildings.php',
    data: "building=" + building,
    dataType: "json",
    complete: function (response) {
        alert(response.name);
    }
});

编辑:所以看起来无论出于什么原因,jQuery无法自动解析它,但JSON.parse(response.responseText)做到了。

您可以使用jQuery.getJSON()并检查响应的contentType

看起来像响应。responseText包含JSON数据包。试试这样做:

var json = JSON.parse(response.responseText); //assume response.responseText is a json string
console.log(json.name);

您的PHP脚本是否在标题中返回正确的MIME类型?如下所示——从PHP脚本返回JSON

如果是,则将其添加到选项中。

dataType: "json",

如果您的内容头是正确的,最容易犯的错误之一是返回引号字符串而不是实际的JSON。ie。实际返回的内容是

"{ '"key'": '"value'" }"
不是

{ "key": "value" }

您的PHP只是返回一个字符串,看起来像JSON对象,但是javascript不够聪明,无法知道您希望它是JSON对象。在对响应进行操作之前,只需解析响应:

$.ajax({
    url: 'buildings.php',
    data: "building=" + building,
    complete: function (response) {
        var json = JSON.parse(response.responseText);
        alert(json.responseText);
        alert(json.name);
    }
});