Ajax请求中的async:false/true的作用

243次阅读
没有评论

test.html

<a href=”javascript:void(0)” onmouseover=”testAsync()”>

asy.js

function testAsync(){
var temp;
$.ajax({
async: false,
type : “GET”,
url : ‘tet.php’,
complete: function(msg){
alert(‘complete’);
},
success : function(data) {
alert(‘success’);
temp=data;
}
});
alert(temp+’ end’);
}

tet.php

<?php

echo “here is html code”;
sleep(5);

?>

async: false,(默认是 true);
如上:false 为同步,这个 testAsync() 方法中的 Ajax 请求将整个浏览器锁死,
只有 tet.php 执行结束后,才可以执行其它操作。

当 async: true 时,ajax 请求是异步的。但是其中有个问题:testAsync() 中的 ajax 请求和其后面的操作是异步执行的,那么当 tet.php 还未执行完,就可能已经执行了 ajax 请求后面的操作,
如:alert(temp+’ end’);
然而,temp 这个数据是在 ajax 请求 success 后才赋值的,结果,输出时会为空。

如果想获取 ajax 获取的数据然后再全局变量中调用,那么要设置 async: false


DEMO_two

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="../javascripts/jquery-2.1.4.js"></script>
    <script>window.onload = function () {$.post("Handler.ashx", {flag: 1}, function (_data) {if (_data) {
                var html = "";
                html += "<table border='1'>";
                for (var i = 0; i < _data.length; i++) {var pj00401 = _data[i].pj00401;
                    html += "<tr>";
                    html += "<td>" + _data[i].pj00402 + "</td>";
                    html += "<td>" + getHtml(pj00401) + "</td>";
                    html += "</tr>";
                }
                html += "</table>";
                $("#div1").append(html);
            }
        }, "json");
        var getHtml = function (_pj00401) {
            var _html = "";
            $.ajaxSettings.async = false;
// 重要设置
            $.get("Handler.ashx", {flag: 102, pj00401: _pj00401}, function (_data) {if (_data) {
                    _html = "<table>";
                    _html += "<tbody>";
                    for (var i = 0; i < _data.length; i++) {
                        _html += "<tr>";
                        _html += "<td>" + _data[i].pj00402 + "</td>";
                        _html += "</tr>";
                    }
                    _html += "</tbody>";
                    _html += "</table>";
                }
            }, "json");
            return _html;
        }
    } </script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
正文完
有偿技术支持加微信
post-qrcode
 
评论(没有评论)
验证码