简体   繁体   中英

Run Javascript after XMLHttpRequest has been finished

My Problem is that the JavaScript is faster than the 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. But it only loads the list in the select fields but it runs the JavaScript part

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?

I think what you want its add to the select another js function like:

And in the js

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

Not sure if i get what you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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