如何遍历JSON AJAX响应? [英] How to loop through JSON AJAX response?

查看:82
本文介绍了如何遍历JSON AJAX响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从ajax查询中得到一个数组

I get an array from my ajax query

....
success:function(response){
 alert(response); 
}
....

我想创建一个jQuery循环,为作为JSON返回的数组的每个元素触发一个alert().

I would like to create a jQuery loop which fires an alert() for each element of the array returned as JSON.

推荐答案

如果它是有效的JSON,则可以使用$ .each()

If its a valid JSON you can use $.each()

$.each()或jQuery.each()用于迭代javascript对象和数组.

$.each() or jQuery.each() is used for iterating over javascript objects and arrays. 

示例:在下面的示例中,intArray是一个JavaScript数组.所以 遍历数组中的元素,我们使用$ .each()函数. 请注意,此功能有2个参数

Example : In the example below intArray is a JavaScript array. So to loop thru the elements in the array we are using $.each() function. Notice this function has 2 parameters

  1. 我们要迭代的JavaScript对象或数组
  2. 将在每次迭代中执行的回调函数

$(document).ready(function () {            
  var  intArray = [100, 200, 300, 400, 500];            
  var  result =  '';           
  $.each(intArray,  function (index, element) {               
    result +=  'Index = '  + index +  ', Value = '  + element +  '<br/>';  
    alert(element); // alert the values 
  });           
  $('#resultDiv').html(result); //insert the concatinated values inside a div 

         
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head>             
  </head >
     <body>     
       <div  id = "resultDiv" >
       </div>
     </body>
</html>

这篇关于如何遍历JSON AJAX响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆