我是jquery和JSON的新手。我有以下JSON结构。
{
"address":{
"suburb":[
"HACKHAM WEST",
"HUNTFIELD HEIGHTS",
"ONKAPARINGA HILLS",
"m"
],
"state":"SA"
}
}
所以基本上就是上面的反应:
$.ajax({
type:'POST',
url: 'getAddress.php',
data:postCode='+postCode',
success: function(response) {
alert(response)
}
});
所以,我想要的是一个包含状态的变量,以及一个包含郊区的数组。
答案 0 :(得分:5)
检查您是否有有效的Ajax请求:
$.ajax({
type: "POST",
url: "getAddress.php",
data: {
postCode : postCode // data as object is preferrable
},
dataType: "json", // to parse response as JSON automatically
success: function(response) {
var state = response.address.state;
var suburbs = response.address.suburb;
}
});
答案 1 :(得分:3)
这应该可以解决问题
$.ajax({type:'POST',
url: 'getAddress.php',
dataType: 'json',
data:'postCode='+postCode,
success: function(response) {
var state = response.address.state;
var suburbs = response.address.suburb;
}
});
添加了dataType:'json'
并修复了data
参数。
答案 2 :(得分:1)
您需要解析所获得的JSON。 $.ajax
可以为您做到这一点。
$.ajax({
type:'POST',
url: 'getAddress.php',
data: 'postCode='+postCode, // make sure this line is correct
dataType: 'json', // this tells jQuery to parse it for you
success: function(response) {
var state = response.address.state;
var suburbs = response.address.suburb;
}
});