我的javascript代码没有按正确的顺序执行

可能重复:
你如何让javascript代码按顺序执行*

var cek = false; function checkForm() { var user = document.forms["LoginForm"]["user"].value; var pwd = document.forms["LoginForm"]["pwd"].value; AJAXfunc("checkidpass.php?id="+user+"&pass="+pwd,function() { if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) { $("#LoginRes").html(xmlhttp.responseText); if (xmlhttp.responseText == "") cek = true; } }); //---> 1 return cek; //---> 2 } 

我想问为什么“返回cek;” (第2部分)在AJAXfunc(第1部分)之前执行? 我想知道如何以正确的顺序执行它。

谢谢你的帮助 !

要了解您的问题,您需要了解异步方法。 一个简单的谷歌将为您提供大量的阅读材料。 我建议从这里开始:

掌握Ajax,第2部分:使用JavaScript和Ajax进行异步请求

提示:你现在所做的事情永远不会奏效 – 除非你选择让它成为同步function(不推荐)。

那是因为AJAX调用是异步的。

AJAXfunc调用在return语句之前执行,但是您在AJAXfunc调用中提供的匿名函数稍后会被调用。

return语句之前运行回调的方法是使AJAX调用同步。 然而,这通常不是一个好主意,因为这将使浏览器在等待响应时冻结。

处理此问题的常用方法是在checkForm函数中使用回调:

 function checkForm(callback) { var user = document.forms["LoginForm"]["user"].value; var pwd = document.forms["LoginForm"]["pwd"].value; AJAXfunc("checkidpass.php?id="+user+"&pass="+pwd,function() { if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) { $("#LoginRes").html(xmlhttp.responseText); callback(xmlhttp.responseText == ""); } }); } 

用法:

 checkForm(function(cek) { if (cek) { // ok } else { // not ok } }); 

Javascript是异步的,因此像你这样的异步函数AJAXfunc在程序完成之前不会阻止你的程序。 这就是为什么事件和回调在javascript中大量使用的原因。

例如,带回调的代码看起来像:

 function checkForm(callback) { var user = document.forms["LoginForm"]["user"].value; var pwd = document.forms["LoginForm"]["pwd"].value; AJAXfunc("checkidpass.php?id="+user+"&pass="+pwd,function() { if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) { $("#LoginRes").html(xmlhttp.responseText); if (xmlhttp.responseText == "") return callback(true); } return callback(false); }); } checkForm( function (result) { var cek = result; // Rest of your code for manipulating DOM or something else where you need cek. } ); 

您最好重新构造代码,以便在获得响应时触发回调。

即。 1. make checkForm有一个回调参数2.用结果3激活该回调。将其余的代码放在回调中而不是跟随函数的返回

例如:

 // before (wrong): result = checkForm(); handleResult1(result); handleResult2(result); // after (correct): checkForm(function(result) { handleResult1(result); handleResult2(result); }