JQueryAjax Tutorial: asynchronous and synchronous

Source: Internet
Author: User
The default ajax call method in jquery is asynchronous, so an error occurs if you do not pay attention to it. For example, ajax is required to check whether a number is an odd or even number. Someone writes the following code without thinking about it: 123456789101112131415161718192021222324252627 $ (function () {$ (# btnte jquery's default ajax call method is asynchronous, so an error will occur if you do not pay attention to it. For example, ajax is required to check whether a number is an odd or even number. Someone writes the following code without thinking:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

$ (Function (){

$ ("# Btntest"). click (function (){

Vars = checkodd (5 );

Alert (s );

});

});

Function checkodd (I ){

Var options = {

Type: 'post ',

Url: "test. ashx ",

Data: {"I": I },

Success: function (result ){

If (result. code> 0 ){

Return "odd ";

}

Else {

Return "even ";

}

},

DataType: "json ",

Error: function (result ){

Alert ("error ");

}

};

$. Ajax (options );

}

Test. after receiving the request, ashx returns {"code": "1"} In json format if the input I is an odd number. If it is an even number, it returns {"code ": "-1 "}.
After you write this code, the result is as follows:

This is because the return in the success method is only the return value of the success method, rather than the return value of checkodd. Such return values cannot be directly obtained by the checkodd method.
Therefore, someone modifies
Double-click all code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

Function checkodd (I ){

Varreturnvalue;

Var options = {

Type: 'post ',

Url: "test. ashx ",

Data: {"I": I },

Success: function (result ){

If (result. code> 0 ){

Returnvalue = "odd ";

}

Else {

Returnvalue = "even ";

}

},

DataType: "json ",

Error: function (result ){

Alert ("error ");

}

};

$. Ajax (options );

Returnreturnvalue;

}

Obtain the return value through an intermediate variable returnvalue. It looks good. However, the result after running is:

The reason is very simple. By default, ajax is executed asynchronously. That is to say, the value of returnvalue has been returned before the ajax method is completed, that is, the success method is not completed, of course, the undefined value is obtained.
Jquery ajax provides the async parameter. By setting the value of this parameter to false, asynchronous execution can be avoided. Therefore, someone modifies the code again:
Double-click all code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

Function checkodd (I ){

Varreturnvalue;

Var options = {

Type: 'post ',

Url: "test. ashx ",

Data: {"I": I },

Async: false,

Success: function (result ){

If (result. code> 0 ){

Returnvalue = "odd ";

}

Else {

Returnvalue = "even ";

}

},

DataType: "json ",

Error: function (result ){

Alert ("error ");

}

};

$. Ajax (options );

Returnreturnvalue;

}

This is the last time.

Set async: false so that the following code can be executed only after ajax is executed. Therefore, modify ajax parameters to ensure synchronous operation.
In fact, jquery's ajax essentially calls the XMLHttpRequest object. XMLHttpRequest is an API. Each browser has its own implementation. For example, earlier versions of IE Use ActiveX and Firefox uses XMLHttpRequest objects. This API mainly implements HTTP (S) Communication in javascript. For more information, see http://en.wikipedia.org/wiki/xmlhttprequest.
Directly using this API to implement ajax is difficult. You can refer to the following code.
Double-click all code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Function useXMLHttpRequest (){

Var xmlhttp = newXMLHttpRequest ();

Xmlhttp. open ("POST", "test. ashx", false );

Xmlhttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded; charset = UTF-8 ");

Xmlhttp. onreadystatechange = function (){

If (xmlhttp. readyState = 4 ){

// Alert (xmlhttp. responseText );

If (xmlhttp. responseText. code> 0 ){

Alert ("odd ");

}

Else {

Alert ("even ");

}

}

};

Xmlhttp. send ("I = 5 ");

Alert ("finished ");

}

The above code implements the ajax function of jquery, which is difficult to compile and requires some parameters, among which xmlhttp. open ("POST", "test. in ashx ", false);, the final parameter" false "or" true "controls whether ajax is synchronous or asynchronous, which is the same as the meaning in the previous ajax example of jquery. Therefore, jquery encapsulates this API, making it easier to operate ajax with jquery.
Note that Javascript itself runs in a single thread. All mainstream browsers only provide one thread to execute Javascript. Therefore, Javascript cannot enable additional threads (unless Web Workers is used, the latest browsers such as Safari, Chrome, Opera and Mozilla Firefox support WebWorkers and IE10 ). Events in Javascript are linearly executed. Using a task queue, events can be considered as first-in-first-out mode. Therefore, all Asynchronous Javascript implementations are hypothetical and implemented through timers.
Javascript runs in a single thread. It does not mean that ajax runs in a single thread. Because ajax is implemented through the XMLHttpRequest API, the browser provides additional threads to process httprequest. Once the request is processed, it triggers an event and adds the event to the javascript task queue until javascript processes the event.
Related Article

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.