简体   繁体   中英

How do I send through ajax each element from the following array?

Send through ajax each element from the following array. Note: Each request must be made once the previous has finished. ['This', 'is', 'a', 'fake, 'array']

I am a little confused by this question because I thought Ajax is asynchronous, meaning the script keeps sending requests to the server without waiting for the reply.

***Was downvoted so going to clarify something: It specifically states in the problem statement that the REQUEST must be made synchronously. I do realize that there are better ways of doing this via def/promises asynchronously so order remains for the result but that isn't the request.

Ajax has a async parameter you can set to false which will block until call completion.

Per documentation:

async (default: true) Type: Boolean By default, all requests are sent asynchronously (ie this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().

http://api.jquery.com/jquery.ajax/

Example:

$.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);}  
 }); 
});

Working fiddler example: https://jsfiddle.net/zm9bb4xk/

I was talking about JQuery Ajax .

So, first, based on documentation, Ajax has many events that run at certain times, for example:

beforeSend (Local Event)

This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.)

error (Local Event)

This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).

complete (Local Event)

This event is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.

success (Local Event)

This event is only called if the request was successful (no errors from the server, no errors with the data).

More in documentation.

Second, following your example (you have to complete this with your own data and this code is not tested, maybe it has some small sintax errors), an approximation is:

//  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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM