Home > Article > Web Front-end > jQuery ajax json data traversal code
Let me tell you my needs first: after making an ajax request, the following json data is passed back in the background.
The specific implementation code is as follows:
JavaScript code
{ "data":[ {"id":"1","name":"选择A","value":"A"}, {"id":"2","name":"选择B","value":"B"}, {"id":"3","name":"选择C","value":"C"} ] }
The above json data class is parsed in the success function of jquery
JavaScript code
$.ajax({ type: "POST", url: "xxx.do", dataType : "json", // 指定返回类型 data: {xxx:"yyy"}, // 传递到后台的参数 success: function(data) { $.each(data, function(index,values){ // 解析出data对应的Object数组 $.each(values,function(index2,value){ // 遍历Object数组 ,每个对象的值存放在value ,index2表示为第几个对象 // 根据自己的逻辑进行数据的处理 alert(value.name + " " + value.value); // TODO: 逻辑 }); }); }, error : function() { alert("系统出现问题"); } });
Continue with an example
This chapter shares a code example, which is the ajax request processing for JSON data encapsulated by jQuery.
The code is relatively simple and can be skimmed by experienced personnel. Beginners can use it as a reference.
The code is as follows:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <title>PHP中文网</title> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <script> $(document).ready(function(){ $("#bt").click(function(){ $.ajax({ type: "get", dataType: "json", url: "demo/jQuery/ajax/txt/json.txt", success: function(msg){ var data = msg str=""; $.each(data,function(index, n){ str=str+data[index].webName+","+data[index].url+","+data[index].age+"<br/>"; }); $("#show").html(str); } }); }) }) </script> </head> <body> <div id="show"></div> <input type="button" id="bt" value="查看效果"/> </body> </html>
The above is the jQuery ajax json data traversal code introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message. Editor Will reply to everyone promptly. I would also like to thank you all for your support of the PHP Chinese website!
For more jQuery ajax json data traversal code related articles, please pay attention to the PHP Chinese website!