json how to make the result to alter as expected value

时间:2015-10-06 08:47:05

标签: jquery json ajax

I have an ajax using jquery and the ajax response is a json. My ajax as follows:

$.post("updatechatusers.php", {courseid:cid}, function (data) {
         console.log(data);

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


     },"json");

But I am getting my console as follows:

 [Object, Object, Object, Object]

id:1 name:test1 .....

My json is as follows:

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

I got output as id:1 name:test1 .....

I do not want id: name: , What I need is 1 test1....... Without using the labels of json.

3 个答案:

答案 0 :(得分:2)

It should be $.each like this:

......
        var json = $.parseJSON(data);
        $.each(json, function(i,val){ // See the change here
          $.each(val,function(k,v){
             console.log(k+" : "+ v);
          }); 
        });  
.......   

From the Docs. http://api.jquery.com/jquery.each/

Edit: Seems like this is what you want.

var json = $.parseJSON(j);
$.each(json,function (i, val) {
  console.log(val.id+' '+val.name)
});

答案 1 :(得分:1)

假设您需要像此1-test1,2-test2,3-test3,4-test4,5-test5,

这样的逗号分隔数据

代码是



var j = '[{"id":"1","name":"test1"},{"id":"2","name":"test2"},{"id":"3","name":"test3"},{"id":"4","name":"test4"},{"id":"5","name":"test5"}]';
console.log(JSON.parse(j))
var json = $.parseJSON(j);
var temp = ''
$(json).each(function(i, val) {
  temp += val.id + '-' + val.name + ',';
});
console.log(temp)




答案 2 :(得分:0)

You can use ajax POST like this. Hope it will be helpful for you.

var data = "{'courseid':"+cid+"}";
    $.ajax({
        url: "updatechatusers.php",
        contentType: "application/json",
        dataType: "json",
        data: data,
        type: "POST",
        beforeSend: function (jqXHR, settings) { },
        success: function (result, textStatus, jqXHR) {
            console.log("JSOn Result======"+JSON.stringify(result));
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("error " + jqXHR.responseText + " " + textStatus + " " + errorThrown);
        }
    });