The question of assigning a value to a global variable by the return value of a JavaScript callback function

Source: Internet
Author: User

In JQuery, you encounter an issue where the $.get (Url,data,callback,type) or $.post (Url,data,callback,type) return value assigns a value to a global variable:

For example:

<script type= "Text/javascript" src= "jquery-1.4.min.js" ></script> <script language= "JavaScript" >     var mm = 1;     $.getjson ("/test/getisexist",               "3", Id2: "5"},                 function(data) {                    var ret = data;                   var show_info = eval_r (ret);                    = Show_info[0].id;     });      </script>

Want to use JavaScript to take the value of getisexist in TestController, assign to test.aspx in the global variable mm, but the value returned only in $.getjson in the role of MM is 8, in the global display is still 1, how to solve this problem?

Problem Reason: Ajax is asynchronous javascript&xml, browser parsing page, JS just execute the current code, sequential execution. Send the request, that is the request response, it does not matter, just continue to execute the code in front of it, so the Ajax response will continue to go down, then your global mm is still the initial value (here is 1), if you are in the callback function (data) {} Inside alert words, it's going to be 8. One way to say it upstairs. The other is to change asynchronous to synchronous Async:false

Method One: Implement in the callback function

Method Two: Implement outside the callback function

<script type= "Text/javascript" >$ (document). Ready (function(e) {$ ("#register"). Click (function(e) {
varresult=true; $.ajax ({URL:"Check_vcode.php", Async:false, type:"POST", data: {vcode:$ ("#vcode"). Val ()}, Success:function(msg) {if(Msg.indexof ("error")!=-1){ $("#msg"). HTML (msg); Result=false; } } }); returnresult; }); });
</script>

The question of assigning a value to a global variable by the return value of a JavaScript callback function

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.