我使用php,并使用json_encode()函数返回/返回json数组。我使用的是jquery ajax,并成功地检索到了以下数据:
[{"id":"1132","city":"Manila Central Post Office","province":"Manila"}]
我在我的Javascript btw:上使用了这段代码
var val = jQuery.parseJSON(JSON.stringify(result));
当我试图访问阵列上的数据时,比如:
console.info(val.city); // results to undefine
它给了我"未定义"的结果。我试着在循环中做For仍然不起作用。也许我做错了什么,任何帮助都会很棒。谢谢
Ajax代码:
$.ajax({
type: 'POST',
url: path,
cache: false,
data: postData,
success: function (result) {
var val = jQuery.parseJSON(JSON.stringify(result, false, replacer));
var val2 = jQuery.parseJSON(val);
console.info(val2);
console.info(val2.id);
},
error: function (e) {
$("#sys_msg").html(e);
$("#myModal").modal({
show: true,
backdrop: false,
keyboard: true
});
}
});
val
是一个数组。您需要指定如下索引。
var result = [{ "id": "1132", "city": "Manila Central Post Office", "province": "Manila" }];
var val = jQuery.parseJSON(JSON.stringify(result));
alert(val[0].city);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这里val
是一个对象数组,因此不能通过调用val.city
直接访问city
值。如果返回的数据已经使用json_encode()
进行了编码,那么您只需要使用$.parseJSON(data)
。下面的代码片段展示了如何做到这一点-
var temp = '[{"id":"1132","city": "Manila Central Post Office", "province":"Manila"},{"id":"1133","city": "Another Test Post Office", "province":"Test"}]'; //Defined temp as string since the data response returned from the server should also be a json encoded string.
var val = $.parseJSON(temp);
$.each(val, function(index, item) {
var city = item.city;
$('.container').append('City: '+city+'<br/>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="container"></div>
看,这个问题可以通过dataType:"json"
轻松解决。如果您的ajax代码中没有附加这个,那么返回的响应将是一个json字符串,在这种情况下,只需要使用jQuery.parseJSON()
或JSON.parse()
来解析它。
因此,您可以将dataType
添加到ajax中,或者只解析它
success: function(result){
var val = jQuery.parseJSON(result); // or JSON.parse(result);
console.info(val[0].city);
},
带dataType
:
$.ajax({
type: 'POST',
url: path,
cache: false,
data: postData,
dataType: 'json', //<-----add this here
success: function(result) {
for (o in result) { // <----and just use this way
console.info(o.city);
}
},
error: function(e) {
$("#sys_msg").html(e);
$("#myModal").modal({
show: true,
backdrop: false,
keyboard: true
});
}
});
您不必stringify
,然后再次将其解析为JSON。您可以在AJAX中添加dataType: "json"
。
$.ajax({
type: 'POST',
url: path,
cache: false,
data: postData,
dataType: "json",
success: function (result) {
console.info(result);
console.info(result.id);
},
error: function (e) {
$("#sys_msg").html(JSON.stringify(e));
$("#myModal").modal({
show: true,
backdrop: false,
keyboard: true
});
}
});