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