jquery使用ajax时有个参数async,对于他的作用一直比较迷茫,下面用一个例子来说明他会带来什么效果。
客户端:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title> New Document </title>
<script type="text/javascript" src="...../jquery.js"></script>
</head>
<body>
<script type="text/javascript">
<!--
jQuery(function($){
$.ajax({
type: "get",
async: false,
url: "test.php",
dataType: "jsonp",
jsonp: "callbackparam",
jsonpCallback: "success_callback",
beforeSend:function(){
$('#block').html('加载中...');
},
success: function(data){
$('#block').html(data.a);
},
error: function(){
alert('fail');
}
});
$.ajax({
type: "get",
url: "aa.php",
dataType: "text",
success: function(data){
alert(data);
},
error: function(){
alert('fail');
}
});
});
//-->
</script>
<div id="block"></div>
</body>
</html>
test.php:
<?php
$arr = array(
'a' => 'aaa',
'b' => 'bb'
);
$callback = $_GET['callbackparam'];
$json = json_encode($arr);
header("Content-type: text/html; charset=utf-8");
sleep(5);
echo $callback . "(" . $json . ")";
?>
aa.php
<?php
header("Content-type: text/html; charset=utf-8");
echo "tttttttt";
?>
上面代码演示可知,anysc为false时,后面的请求aa.php不会被发送,服务器处于等待状态,当test.php请求返回结果时,aa.php请求被发送。若anysc为true,可以看到test.php在请求的过程中,aa.php的请求结果已经返回,因为test.php设置了sleep(5)来延长请求时候。