ajax同步異步調用

test.html

<a href="javascript:void(0)" οnmοuseοver="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後才賦值的,結果,輸出時會爲空。
發佈了33 篇原創文章 · 獲贊 18 · 訪問量 123萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章