Javascript 如何在 jQuery Ajax 成功回调中处理我的 JSON 数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5661647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:20:02  来源:igfitidea点击:

How to handle my JSON data in jQuery Ajax success callback?

javascriptjqueryajaxjson

提问by Mellon

If I have a ajax call:

如果我有一个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
  }
});

Server returned to my js the following JSONdata

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

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

In my jQuery AJAX success callback function, how to extract the value of "name", value of "address" (which is a list of object) elegantly?

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

I am not experienced with jQuery and JSON data handling in javascript. So, I would like to ask some suggestions on how to handle this data efficiently. Thanks.

我对 javascript 中的 jQuery 和 JSON 数据处理没有经验。所以,我想问一些关于如何有效处理这些数据的建议。谢谢。

回答by Felix Kling

A JSON string gets parsed into a JavaScript object/array. So you can access the values like you access any object property, array element:

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

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

Do access the values inside each address, you can iterate over the array:

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

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

If you have not so much experience with JavaScript, I suggest to read this guide.

如果您对 JavaScript 没有太多经验,我建议您阅读本指南