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リクエストでメッセージボックスから外れた後、1秒後に「未定義」のメッセージボックスから外れます。

質問は、なぜアラート(応答)を実行するのかということです。前のステップを終了する前に、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 に答える