【问题标题】:How to handle my JSON data in jQuery Ajax success callback?如何在 jQuery Ajax 成功回调中处理我的 JSON 数据?
【发布时间】:2011-08-05 10:06:48
【问题描述】:

如果我有一个 ajax 调用:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: function(json_data){
    //What's the efficient way to extract the JSON data and get the value
  }
});

服务器向我的 js 返回以下 JSON 数据

{"contact":[{"address":[{"city":"Shanghai","street":"Long
            Hua Street"},{"city":"Shanghai","street":"Dong Quan
            Street"}],"id":"huangyim","name":"Huang Yi Ming"}]}

在我的jQuery AJAX成功回调函数中,如何提取“name”的值,“address”的值(这是一个对象列表) 优雅吗?

我没有使用 javascript 处理 jQuery 和 JSON 数据的经验。所以,我想就如何有效地处理这些数据提出一些建议。谢谢。

【问题讨论】:

    标签: javascript jquery ajax json


    【解决方案1】:

    JSON 字符串被解析为 JavaScript 对象/数组。因此,您可以像访问任何对象属性、数组元素一样访问值:

    var name = json_data.contact[0].name;
    var addresses = json_data.contact[0].address;
    

    访问每个地址内的值,你可以遍历数组:

    for(var i = addresses.length; i--;) {
        var address = addresses[i];
        // address.city
        // address.street
        // etc
    }
    

    如果你对 JavaScript 没有太多经验,我建议read this guide

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 1970-01-01
      • 2011-04-14
      • 2023-03-10
      相关资源
      最近更新 更多