2015-10-06 35 views
0

我有一个使用jquery的ajax,而ajax响应是一个json。我的AJAX如下:json如何使结果改变为预期的值

$.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"); 

但我得到我的控制台如下:

[Object, Object, Object, Object] 

id:1 name:test1 ..... 

json如下:

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

我输出ID:1名: test1 .....

我不想要id:name:,我需要的是1 test1....... Witho ut使用json的标签。

+0

你的代码是工作的罚款[这里](http://jsfiddle.net/zsLk691z /)。尝试重现问题,以便我们可以修复 –

+0

@JSantosh我得到作为id:1名称:test1。我不想要id:name:。我蚂蚁1 test1 – Santhucool

+0

你可以发布你的期望。在OP中,你说你有错误。 –

回答

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)

+0

非常感谢你的朋友! – Santhucool

+0

很高兴帮助:) –

2

应该$.each这样的:

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

从文档。 http://api.jquery.com/jquery.each/

编辑:看起来像这样是你想要的。

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

确定好友,它现在正在工作,问题是我把json放在ajax响应中。当我删除它,现在它继续工作 – Santhucool

+0

更新请看看! – Santhucool

+0

@Santhucool在这里检查http://jsfiddle.net/xv1ouvqr/ –

1

您可以像这样使用ajax POST。希望它对你有所帮助。

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); 
     } 
    }); 
+0

已更新。看看 – Santhucool