1

我是 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)
    }
});

所以,我想要得到的是一个包含状态的变量和一个包含郊区的数组。

4

3 回答 3

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;
    }
});
于 2012-06-26T17:43:59.873 回答
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参数。

于 2012-06-26T17:43:14.383 回答
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;
    }
});
于 2012-06-26T17:44:44.207 回答