Ajax請求中的async:false/true的作用[轉]


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后才賦值的,結果,輸出時會為空。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM