When an Ajax loop is called, only the last value is returned, and the last data is executed in the background

Source: Internet
Author: User

1.

Code:
var i;
for (i=0;i<10;i++) {
Ajaxservise (i);
}

Calling the Ajax method in the for loop complements the data on the page, which is wrong, and does not execute the Ajax method every time the for loop is executed, but instead executes the Ajax method at the end of the For loop, which results in Ajax being executed only once . However when modified as follows:

for (i=0;i<10;i++) {
Alert ("AA");
Ajaxservise (i);
}
Unlike the above, a form alert pops up each time it is called ("content is free") so that the content is displayed correctly on the page instead of a single piece of content

Cause: The For loop is single-threaded in JS, he will execute the next step after the for loop, and alert closes the loop, letting the program respond once, and calling the Ajax method again, but we can't let the alert method appear in the program.

(This method is displayed correctly in the foreground, but is still the last value when the background data is called)
Workaround:
var i=0;
var sum=10;
var time;
Ajaxservise (i) {
if (i==sum) {
Cleartimeout (time);
}
i=i+1;
Time = SetTimeout (Ajaxservise (), 10);
........................
..................
............
......
}

This is called with the settimeout (Ajax ()) method, settimeout the method executes and then executes the Ajax () method again, with settimeout and cleartimeout to solve the problem perfectly.

Ps:settimeout is pseudo-multithreading.

2, whether to fill in the synchronization of the field.

When an Ajax loop is called, only the last value is returned, and the last data is executed in the background

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.