简体   繁体   English

XMLHttpRequest完成后运行Javascript

[英]Run Javascript after XMLHttpRequest has been finished

My Problem is that the JavaScript is faster than the XMLHttpRequest. 我的问题是JavaScript比XMLHttpRequest更快。 I don't want to solve it with: 我不想用以下方法解决它:

setTimeout(function() {}, 100);

My Code: 我的代码:

function change_country(id) {

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }
    else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

            var data = JSON.parse(xmlhttp.responseText);

            document.getElementById("continent").value = data.continent;
            document.getElementById("country").value = data.country;

        }
        xmlhttp.open("GET", "request_country_change.php?id=" + id, true);
        xmlhttp.send();
    }
}

The code is only an example, not the original. 代码只是一个例子,而不是原始代码。 It should be a change form. 它应该是一种变化形式。 So in this example it loads the list of all continents in the select field. 因此,在此示例中,它会在选择字段中加载所有大陆的列表。 And it select the continent which is related to the id and the same with the countries. 它选择与id相关的大陆,与国家相同。 But it only loads the list in the select fields but it runs the JavaScript part 但它只在选择字段中加载列表,但它运行JavaScript部分

document.getElementById("continent").value = data.continent;
document.getElementById("country").value = data.country;

to early. 到了早。 If I make between an alert or setTimeout it works, but can I solve it in another way? 如果我在警报或setTimeout之间进行操作,但我可以用其他方式解决吗?

I think what you want its add to the select another js function like: 我想你想要它添加到select另一个js函数,如:

And in the js 并在js

function storeContinent(val){
     document.getElementById("continent").value = val;
}

Not sure if i get what you want 不确定我是否得到了你想要的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM