Loop Ajax Request Problem

Source: Internet
Author: User

The project development process has encountered this requirement: the need to loop through the Ajax requests, the request parameters and the circular index.
The first implementation is similar to the following method, and the result is that the parameter data sent to the backend is the index of the last loop.

1  for (var i=0; i<10; i++) {2     $.get (url,{param:i},function() {}); 3 }

This is because JS does not have a block-level scope, and the code block used in the for loop is actually the same, the last index value.
JS has a function scope, so you can use the JS closure feature to make each request in a For loop use the index value differently. Implementation code:

1  for (var i=0; i<10; i++) {2     (function(seq) {3         $.get (url,{param:seq},function() {}); 4     }) (i); 5 }

This is because in the function scope, intrinsic functions can access the parameters and variables of the external function that defines them, and the intrinsic function has a longer life cycle than the external function; In the above example, $.get () is an intrinsic function, and function (seq) {} is an external function. The intrinsic function can directly use the parameter seq of the external function. Since the external function executes the function immediately, the external function creates a context environment for the intrinsic function, and the parameter seq of the external function is part of the context, which exists in the life cycle of the intrinsic function. Based on the fact that, in a single loop, the outer function executes at the end and the life cycle of the outer function ends, but the external function is still valid for the context created by the intrinsic function. Because the arguments are different, the external function creates a different context each time it executes. For intrinsic functions, execution uses a parameter seq that exists in the context, and uses a different SEQ value for different context environments. Personal understanding

Loop Ajax Request Problem

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.