Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
789 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

***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 (i.e. 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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...