jquery ajax这async超级解析

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)来延长请求时候。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值