javascript如何foreach循环数组

时间:2016-08-16 20:26:02

标签: javascript php jquery arrays for-loop

我有一个看起来像这样的数组

var ids = ["id1","id2","id3","id4"]

我想循环遍历数组并提取每个id并将其传递给ajax。所以它会自动填写一些输入字段

我熟悉PHP,我会用

foreach($array as $temporaryvariable){
  // do stuff with $temporaryvariable
}

所以我正在寻找Javascript或JQuery等价物,所以我的最终代码将如下所示

var ids = ["id1","id2","id3","id4"]

foreach(ids as id){
$.ajax({
  url: "../folder/lookupserver.php",
  type: "POST", 
  data: {
    'id' : id//each of the ids
  },
  dataType: "JSON",
  success:function(data){
    $result= data;
    $('#input field').val($result);
  }
}

7 个答案:

答案 0 :(得分:1)

使用https://learn.jquery.com/using-jquery-core/document-ready/方法:



var ids = ["id1","id2","id3","id4"]
ids.forEach(function(id) {

  console.log(id);
  // here you can have an AJAX

});




这个方法有一个参数:一个函数,它将为数组的每个元素执行。您需要指定要为所选元素调用的名称。就像在PHP中一样:foreach($ids as $id)

答案 1 :(得分:1)

更好,更少服务器密集的方式是传递......

整个数组到服务器,

var ids = ["id1", "id2", "id3", "id4"];

$.ajax({
    url: "../folder/lookupserver.php",
    type: "POST",
    data: {

        'id': ids
    },
    dataType: "JSON",
    success: function (data) {
        $result = data;
        $('#input field').val($result);
    }
});

然后阅读PHP中的数组并使用foreach获取个人ID。

这样您就不会快速连续地向服务器发送这么多请求。

然而...

如果您真的想发送那么多请求,请使用forEach循环。

var ids = ["id1", "id2", "id3", "id4"];

ids.forEach(function (id) {
    /** Your AJAX request here. **/
});

答案 2 :(得分:0)

你可以使用for循环

var ids = ["id1","id2","id3","id4"]
var id;
    for(var i=0; i< ids.length;i++){
       id = ids[i];
       $.ajax({
            url: "../folder/lookupserver.php",
            type: "POST", 
            data: {

                   'id' : id//each of the ids
             },
                    dataType: "JSON",
                    success:function(data){
                           $result= data;
                           $('#input field').val($result);
                                }

         }
     }

答案 3 :(得分:0)

Javascript数组也有foreach函数: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

尝试类似

的内容
var ids = ["id1","id2","id3","id4"].foreach( function(element, index) {
    // custom ajax code here
});

答案 4 :(得分:0)

在Javascript中,这将是一个for循环,如此

示例:

  var ids = ["id1","id2","id3","id4"]

  var i;

  for(i in ids){

        //do whatever here

}

答案 5 :(得分:0)

引起我的注意,我应该提到我在这个解决方案中使用了es6语法。包括对象增强,箭头功能和const关键字。在您自己的项目中使用此代码之前,请务必阅读这些主题。

const ids = ["id1","id2","id3","id4"];

const options = id => ({ 
  url: '../folder/lookupserver.php',
  type: 'POST',
  data: { id },
  dataType: 'JSON'
});

const update = data => $('#update field').val(data);

const request = id => $.ajax(options(id)).done(update);

ids.forEach(request);

答案 6 :(得分:-1)

var ids = ["id1","id2","id3","id4"];
    i=0;
    $(ids).each(function(){
      console.log(ids[i]);
      i++;
    });