如何将数组值传递给函数 javascript

How to pass array value to function javascript

我想知道如何将数组中的值传递给 javascript 中的 ajax 函数。 对于每个 id,调用 javascript 中的函数。 如何传递数组中的每个id并调用函数

var listid=["fund","trans","ins"]; 

getData(id){
var li = $.ajax({
    url: "/en",
    method: 'get',
    global: false,
    async: false,
    data: {
      idvalue: id
    },
    success: function(value) {
      return value;
    }
  }).responseText;
 console.log(JSON.parse(li));

}

您可以对数组使用 map 函数。 它是一个将回调作为参数的 JavaScript 函数。您可以将任何函数作为回调传递,它会为该数组中的每个值调用它。

将循环应用于您的 id 数组。

var listid=["fund","trans","ins"]; 

for(let i = 0, len = listid.length; i < len; i++) {
    getData(listid[i]);
}

您可以使用 $.each 作为您的数组值

var listid=["fund","trans","ins"]; 
    $.each(listid, function( index, value ) {
      //console.log( index + ": " + value );
      getData(value );  //uncomment this for actual implementation
    });
    
    function getData(id){
    var li = id;
    /*$.ajax({
      url: "/en",
      method: 'get',
      global: false,
      async: false,
      data: {
        idvalue: id
      },
      success: function(value) {
        return value;
      }
    }).responseText;*/
    //console.log(JSON.parse(li));
    console.log(li);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

您可以使用:

listid.forEach(function (id) { getData(id) });

var listid=["fund","trans","ins"]; 

for(var i = 0 ; i < listid.length ; i++){
getData(listid[i]);

}
function getData(id){
var li = $.ajax({
    url: "/en",
    method: 'get',
    global: false,
    async: false,
    data: {
      idvalue: id
    },
    success: function(value) {
      return value;
    }
  }).responseText;
 console.log(JSON.parse(li));

}

您可以轻松地使用 forEach 遍历列表。

var listid=["fund","trans","ins"]; 

listid.forEach(function(id) {
   getData(id);
});

function getData(id) {
   var xhr = $.ajax({
    url: "/en",
    method: 'get',
    global: false,
    async: false,
    data: {
      idvalue: id
    },
    success: function(value) {
      return value;
    }
  }).always(function(data,  textStatus, jqXHR) {
      // deal with the data
  })
}

如果您使用的是较新版本的 Jquery,则 jqXHR.success()、jqXHR.error() 和 jqXHR.complete() 回调已从 jQuery 3.0。 您可以改用 jqXHR.done()、jqXHR.fail() 和 jqXHR.always()。

function getData(id) {
   var xhr = $.ajax({
    url: "/en",
    method: 'get',
    global: false,
    async: false,
    data: {
      idvalue: id
    },
    success: function(value) {
      return value;
    }
  })
  .done(function(data, textStatus, jqXHR ) {
    // do something with value
  })
  .fail(function(jqXHR, textStatus, errorThrown) {
    alert( "error" );
  })
  .always(function() {
    alert( "complete" );
  });
}