将多维JSON数组传递给jQuery函数

Passing Multidimensional JSON Array to jQuery Function

本文关键字:jQuery 函数 数组 JSON      更新时间:2023-09-26

我有一个PHP数组,我想把它传递给调用它的jQuery函数。然而,当我试图检索'lat'的值,我下面做的方式,我得到错误Cannot read property 'lat' of null,显然是因为我不知道如何访问一个多维JSON数组。谁能告诉我怎么做?

PHP数组

Array
(
[0] => Array
    (
        [price] => 1600
        [bedroom] => 1
        [lat] => -71.119385
        [lng] => 42.373917
        [distance] => 6.65195429565453
    )
[1] => Array
    (
        [price] => 1800
        [bedroom] => 1
        [lat] => -71.104248
        [lng] => 42.368172
        [distance] => 4.957829810472103
    )
}

这被编码成

JSON

[{"price":"1600","bedroom":"1","lat":"-71.119385","lng":"42.373917","distance":"6.65195429565453"},{"price":"1800","bedroom":"1","lat":"-71.104248","lng":"42.368172","distance":"4.957829810472103"}]
jQuery

$(function() {
    $("#search_button").click(function(e){
        e.preventDefault();
        var search_location = $("#search_location").val();
        $.getJSON('index.php/main/get_places', {search_location: search_location}, function(json){
            $("#result").html(json.lat);
            console.log(json.lat);
        });
    });
});

json是一个数组,所以它不会有lat的属性。

试题:

json[0].lat

获取第一个对象的属性,例如

$.getJSON('index.php/main/get_places', {search_location: search_location}, function(json){
  $.each(json, function(key, val) {
      console.log(val.lat);
  });
});

json作为对象数组返回,因此需要首先引用标量。将引用更改为json。Lat into json[0]. Lat .

然后,如果你需要的话,你可以写一个for循环并引用它为json[i]。最后,假设I是你的迭代器变量

json是一个对象数组,就像在PHP代码中一样。

所以有两个后期值:

json[0].lat  // and
json[1].lat

json变量本身为空,如错误消息所述。所有关于访问json的子索引或像数组一样遍历它的答案都将因此失败。

查看jQuery的getJSONparseJSON文档。getJSON通过parseJSON传递服务器的响应,将其转换为Javascript对象。parseJSON返回null"如果你没有传递任何东西,一个空字符串,null,或未定义。"

我会使用浏览器的调试器来查看来自服务器的原始http响应,因为这可能是罪魁祸首。

http://api.jquery.com/jQuery.getJSON/

http://api.jquery.com/jQuery.parseJSON/