ajax同步
在使用js做驗證的時候,經常會有這種情況:
比如用ajax驗證用戶名,執行checkForm之后,Ajax正在運行的時候,發現下面的已經執行完了return 操作了,還沒等到ajax返回值就已經結束了check。
其實事情的真相是這樣的,jquery的ajax默認使用的是異步方式進行數據交互,xmlhttp_request.open("GET or POST",URL,bool),第三個參數即為設置異步或者同步。jquery寫法:async = true; ,很久不去用原生js,都是用jq這種快餐寫法,,很多東西都忘了,人也變笨了,,不好不好。。
這種情況其實我們只要設置為async = false;就可以等到ajax執行完畢之后才進行下面操作。
代碼:
<!doctype html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=gbk" />
<script src="http://localhost/javascript/jquery.js" ></script>
function checkform(){
var bool = "true";
$.ajax({
data:"ajax="+$("#name").val(),
url:"a.php",
async:false,
success:function(d){
if(d=='false'){
bool = "false";
}
}
})
alert(bool);
return false;
}
</script>
<title> </title>
</head>
<body>
<form method="post" onsubmit="return checkform();" enctype="multipart/form-data">
<!--<input t="1" type="file" name="test">-->
<input id="name" type="text" name="test">
<input type="submit" value="submit">
</form>
</body>
</html>
轉自:http://hi.baidu.com/a53abc/item/72b10bdbdd05223449e1dd75