将多维JSON数组传递给jQuery函数
Passing Multidimensional JSON Array to jQuery Function
我有一个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的getJSON
和parseJSON
文档。getJSON
通过parseJSON
传递服务器的响应,将其转换为Javascript对象。parseJSON
返回null"如果你没有传递任何东西,一个空字符串,null,或未定义。"
我会使用浏览器的调试器来查看来自服务器的原始http响应,因为这可能是罪魁祸首。
http://api.jquery.com/jQuery.getJSON/http://api.jquery.com/jQuery.parseJSON/相关文章:
- 是否有一个JS/jQuery函数可以获取某个类的每个元素的ID
- 如何在JQuery函数中定义一个值,然后调用另一个函数并使用该值
- 如何从jquery函数返回变量
- 如何将具有文本类型值的var放入jQuery函数中
- Jquery函数在错误的时间提交
- 锚链接无法使用.slideUp jquery函数
- 重新分解jQuery函数
- 如何在视图模型contet更新更新上调用Jquery函数
- 如何向这个javascript/jquery函数添加参数
- 添加类来触发jquery函数
- 更改智能表中的页面将停止JQuery函数的工作
- 使用每500ms运行一次的jquery函数是个好主意吗
- jQuery函数不能只在一个页面上工作
- 如何将jquery函数链接到vanilla选择器
- 仅在小型设备上调用jQuery函数
- 如何将jquery函数仅应用于大屏幕
- 奇怪的jquery函数行为
- Backbone listenTo不将jquery函数作为处理程序进行激发
- 在jquery函数内部设置来自jquery函数的var;t运行
- 从Jquery函数中获取一个变量