javascript how to foreach loop through an array
This question already has an answer here:
A better, less server intensive way would be to pass...
The whole array to server,
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);
}
});
then read the array in PHP
and use a foreach
to get the individual ID's like that.
This way you aren't sending so many requests in rapid successions to the server.
However...
If you really want to send that many requests, you'd use a forEach
loop.
var ids = ["id1", "id2", "id3", "id4"];
ids.forEach(function (id) {
/** Your AJAX request here. **/
});
使用forEach()
方法:
var ids = ["id1","id2","id3","id4"]
ids.forEach(function(id) {
console.log(id);
// here you can have an AJAX
});
Javascript arrays also have a foreach function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Try something like
var ids = ["id1","id2","id3","id4"].foreach( function(element, index) {
// custom ajax code here
});
链接地址: http://www.djcxy.com/p/12072.html