![](/img/trans.png)
[英]In Javascript, when looping through an array of objects, how do I send each element's name to the console?
[英]How do I send through ajax each element from the following array?
通過ajax發送以下數組中的每個元素。 注意:每個請求都必須在前一個請求完成后進行。 ['This','is','a','fake,'array']
這個問題讓我有些困惑,因為我認為Ajax是異步的,這意味着腳本會一直向服務器發送請求,而無需等待答復。
***被否決了,所以要澄清一下:它在問題說明中特別指出必須同步進行REQUEST。 我確實意識到,有更好的方法可以通過def / promises異步執行此操作,因此結果的順序保持不變,但這不是請求。
Ajax有一個異步參數,您可以將其設置為false,它將阻塞直到調用完成。
每個文檔:
async(默認:true)類型:Boolean默認情況下,所有請求都是異步發送的(即默認情況下設置為true)。 如果需要同步請求,請將此選項設置為false。 跨域請求和dataType:“ jsonp”請求不支持同步操作。 請注意,同步請求可能會暫時鎖定瀏覽器,從而在請求處於活動狀態時禁用任何操作。 從jQuery 1.8開始,不建議使用async:false和jqXHR($ .Deferred); 您必須使用成功/錯誤/完成回調選項,而不要使用jqXHR對象的相應方法,例如jqXHR.done()。
http://api.jquery.com/jquery.ajax/
例:
$.each(["This", "is", "a", "fake", "array"], function( index, value ) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
data : { json: JSON.stringify( value ) },
async: false,
success: function(data) { alert(data);}
});
});
工作提琴手示例: https : //jsfiddle.net/zm9bb4xk/
我在談論JQuery Ajax 。
因此,首先,基於文檔,Ajax具有許多在特定時間運行的事件,例如:
beforeSend(本地事件)
此事件在啟動Ajax請求之前觸發,允許您修改XMLHttpRequest對象(如果需要,可以設置其他頭)。
錯誤(本地事件)
僅在請求發生錯誤時才調用此事件(對於請求,您永遠不能同時發生錯誤和成功回調)。
完成(本地活動)
無論請求是否成功,都將調用此事件。 即使對於同步請求,您將始終收到完整的回調。
成功(本地活動)
僅當請求成功時才調用此事件(服務器無錯誤,數據無錯誤)。
其次,按照您的示例 (您必須使用自己的數據來完成此操作,並且此代碼未經測試,可能有一些小的sintax錯誤), 其近似值為:
// Variables
var myArray = ["This", "is", "a", "fake", "array"];
var globalIndex = 0;
// Function for Ajax Calls
function myFunction(){
$.ajax({
url: 'myURL', // Your own controller/url
type: "GET", // Or POST
dataType: "json", // Or other datatype
data: {
arrayContent: myArray[globalIndex] // arrayContent = your controller param name
},
/**
* A function to be called if the request succeeds.
*/
success: function(data) {
alert('Load was performed. Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information! ');
alert(data); // Do what you want with your data, this is an example
globalIndex = globalIndex +1;
// Recursive/next call if current call is finished OK and there are elements
if(globalIndex < myArray.length){
myFunction();
}
},
/**
* A function to be called if the request fails.
*/
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
alert('<p>status code: '+jqXHR.status+'</p><p>errorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
// We don't do a recursive/next call because current call has failed
},
});
}
// First call to myFunction
myFunction();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.