How to parse JSON data with jQuery / JavaScript?

2018-12-31 03:17发布

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

$(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 #cand div I'll get:

[ { "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?

10条回答
ら面具成の殇う
2楼-- · 2018-12-31 03:59

setting dataType:'json' will parse json for you

$.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

var parsedJson = $.parseJSON(jsonToBeParsed);

here is how you can iterate

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

iterate using each

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

http://jsfiddle.net/fyxZt/4/

查看更多
呛了眼睛熬了心
3楼-- · 2018-12-31 04:00

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+'</>');
        }
    }
});
查看更多
萌妹纸的霸气范
4楼-- · 2018-12-31 04:07

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");
            }
        });
查看更多
只若初见
5楼-- · 2018-12-31 04:07

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

  1. in your php file make shure that you print like this
echo json_encode(array_shift($your_variable));
  1. in your success function do this
 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

查看更多
笑指拈花
6楼-- · 2018-12-31 04:09

Json data

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+'</>');
}
});
查看更多
梦该遗忘
7楼-- · 2018-12-31 04:09

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.

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

查看更多
登录 后发表回答