如何使用 jQuery / JavaScript 解析 JSON 数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8951810/
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-27 11:18:37  来源:igfitidea点击:

How to parse JSON data with jQuery / JavaScript?

jqueryajaxjsonparsing

提问by Patrioticcow

I have a AJAX call that returns some JSON like this:

我有一个 AJAX 调用,它返回一些像这样的 JSON:

$(document).ready(function () {
    $.ajax({ 
        type: 'GET', 
        url: 'http://example/functions.php', 
        data: { get_param: 'value' }, 
        success: function (data) { 
            var names = data
            $('#cand').html(data);
        }
    });
});

Inside the #canddiv I'll get:

#canddiv里面我会得到:

[ { "id" : "1", "name" : "test1" },
  { "id" : "2", "name" : "test2" },
  { "id" : "3", "name" : "test3" },
  { "id" : "4", "name" : "test4" },
  { "id" : "5", "name" : "test5" } ]

How can I loop through this data and place each name in a div?

如何遍历这些数据并将每个名称放在一个 div 中?

回答by Darin Dimitrov

Assuming your server side script doesn't set the proper Content-Type: application/jsonresponse header you will need to indicate to jQuery that this is JSON by using the dataType: 'json'parameter.

假设您的服务器端脚本没有设置正确的Content-Type: application/json响应头,您将需要使用dataType: 'json'参数向 jQuery 指示这是 JSON 。

Then you could use the $.each()function to loop through the data:

然后你可以使用该$.each()函数来循环数据:

$.ajax({ 
    type: 'GET', 
    url: 'http://example/functions.php', 
    data: { get_param: 'value' }, 
    dataType: 'json',
    success: function (data) { 
        $.each(data, function(index, element) {
            $('body').append($('<div>', {
                text: element.name
            }));
        });
    }
});

or use the $.getJSONmethod:

或使用以下$.getJSON方法:

$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
    $.each(data, function(index, element) {
        $('body').append($('<div>', {
            text: element.name
        }));
    });
});

回答by Rafay

Setting dataType:'json'will parse JSON for you:

设置dataType:'json'将为您解析 JSON:

$.ajax({
  type: 'GET',
  url: 'http://example/functions.php',
  data: {get_param: 'value'},
  dataType: 'json',
  success: function (data) {
    var names = data
    $('#cand').html(data);
  }
});

Or else you can use parseJSON:

或者你可以使用parseJSON

var parsedJson = $.parseJSON(jsonToBeParsed);

Then you can iterate the following:

然后你可以迭代以下内容:

var j ='[{"id":"1","name":"test1"},{"id":"2","name":"test2"},{"id":"3","name":"test3"},{"id":"4","name":"test4"},{"id":"5","name":"test5"}]';

...by using $().each:

...通过使用$().each

var json = $.parseJSON(j);
$(json).each(function (i, val) {
  $.each(val, function (k, v) {
    console.log(k + " : " + v);
  });
}); 

JSFiddle

JSFiddle

回答by Sarabhaiah Polakam

Try following code, it works in my project:

尝试以下代码,它适用于我的项目:

//start ajax request
$.ajax({
    url: "data.json",
    //force to handle it as text
    dataType: "text",
    success: function(data) {

        //data downloaded so we call parseJSON function 
        //and pass downloaded data
        var json = $.parseJSON(data);
        //now json variable contains data in json format
        //let's display a few items
        for (var i=0;i<json.length;++i)
        {
            $('#results').append('<div class="name">'+json[i].name+'</>');
        }
    }
});

回答by Mohammed Abdelrasoul

 $(document).ready(function () {
    $.ajax({ 
        type: 'GET', 
        url: '/functions.php', 
        data: { get_param: 'value' }, 
        success: function (data) { 
         for (var i=0;i<data.length;++i)
         {
         $('#cand').append('<div class="name">data[i].name</>');
         }
        }
    });
});

回答by Shivam Srivastava

Use that code.

使用那个代码。

     $.ajax({

            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Your URL",
            data: "{}",
            dataType: "json",
            success: function (data) {
                alert(data);
            },
            error: function (result) {
                alert("Error");
            }
        });

回答by elaz

ok i had the same problem and i fix it like this by removing []from [{"key":"value"}]:

好的,我遇到了同样的问题,我通过[][{"key":"value"}]以下位置删除来解决它:

  1. in your php file make shure that you print like this
  1. 在你的 php 文件中确保你像这样打印
echo json_encode(array_shift($your_variable));
  1. in your success function do this
  1. 在你的成功职能中做到这一点
 success: function (data) {
    var result = $.parseJSON(data);
      ('.yourclass').append(result['your_key1']);
      ('.yourclass').append(result['your_key2']);
       ..
    }

and also you can loop it if you want

如果你愿意,你也可以循环它

回答by justnajm

I agree with all the above solutions, but to point out whats the root cause of this issue is, that major role player in all above code is this line of code:

我同意上述所有解决方案,但要指出这个问题的根本原因是什么,上述所有代码中的主要角色是这行代码:

dataType:'json'

when you miss this line (which is optional), the data returned from server is treated as full length string (which is default return type). Adding this line of code informs jQuery to convert the possible json string into json object.

当您错过这一行(可选)时,从服务器返回的数据将被视为全长字符串(这是默认返回类型)。添加这行代码通知 jQuery 将可能的 json 字符串转换为 json 对象。

Any jQuery ajax calls should specify this line, if expecting json data object.

如果需要 json 数据对象,任何 jQuery ajax 调用都应指定此行。

回答by Servesh Mishra

var jsonP = "person" : [ { "id" : "1", "name" : "test1" },
  { "id" : "2", "name" : "test2" },
  { "id" : "3", "name" : "test3" },
  { "id" : "4", "name" : "test4" },
  { "id" : "5", "name" : "test5" } ];

var cand = document.getElementById("cand");
var json_arr = [];
$.each(jsonP.person,function(key,value){
    json_arr.push(key+' . '+value.name  + '<br>');
    cand.innerHTML = json_arr;
});

<div id="cand">
</div>

回答by Guspan Tanadi

Json data

JSON数据

data = {"clo":[{"fin":"auto"},{"fin":"robot"},{"fin":"fail"}]}

When retrieve

取回时

$.ajax({
  //type
  //url
  //data
  dataType:'json'
}).done(function( data ) {
var i = data.clo.length; while(i--){
$('#el').append('<p>'+data.clo[i].fin+'</>');
}
});

回答by Sarah Smith

$.ajax({
  url: '//.xml',
  dataType: 'xml',
  success: onTrue,
  error: function (err) {
      console.error('Error: ', err);
  }
});

$('a').each(function () {
  $(this).click(function (e) {
      var l = e.target.text;
      //array.sort(sorteerOp(l));
      //functionToAdaptHtml();
  });
});