尝试使用jquery迭代JSON结构

use*_*791 1 jquery json

我是jquery和JSON的新手.我有以下JSON结构.

{
   "address":{
      "suburb":[
         "HACKHAM WEST",
         "HUNTFIELD HEIGHTS",
         "ONKAPARINGA HILLS",
         "m"
      ],
      "state":"SA"
   }
}
Run Code Online (Sandbox Code Playgroud)

所以基本上上面就是这样的反应:

$.ajax({
    type:'POST',
    url: 'getAddress.php',
    data:postCode='+postCode',
    success: function(response) {
        alert(response)
    }
});
Run Code Online (Sandbox Code Playgroud)

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

Vis*_*ioN 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;
    }
});
Run Code Online (Sandbox Code Playgroud)

  • @ user933791是的.否则,`getAddress.php`应该在header中发送以下内容类型:`header("Content-Type:application/json");`. (2认同)