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

 posted on 2012-10-09 11:12  叶落☆无声  阅读(3621)  评论(0编辑  收藏  举报