0
function ajax_request(destination_full_url) {

    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert("response: \n" + xmlhttp.responseText);
            return xmlhttp.responseText;

        }
    }

    xmlhttp.open("GET", destination_full_url, true);
    xmlhttp.send();
}



    function third_party_function(obj) {
       var response
       response = ajax_request("info.php?keyword=obj.value");
       alert(response);         
    }


<textarea onkeypress="third_party_function(this);"></textarea>

在带有 ajax 请求的消息框关闭后一秒钟,首先关闭消息框“underfined”。

问题是它为什么运行警报(响应);在完成上一步之前,我如何让它等到 ajax_request() 函数完成后再进入下一行?

4

1 回答 1

0

因为 ajax 是异步的并且默认在后台运行,所以你可以通过从

xmlhttp.open("GET", destination_full_url, true);

xmlhttp.open("GET", destination_full_url, false);

=== 更新 ===

function ajax_request(destination_full_url, callback){
.....
xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert("response: \n" + xmlhttp.responseText);
           callback(xmlhttp.responseText);

        }
    }
...
}

....


function third_party_function(obj) {
       ajax_request("info.php?keyword=obj.value", function(response){alert(response) });

    }
于 2012-08-17T23:36:21.810 回答