简体   繁体   中英

Lines of code before AJAX/XMLHttpRequest Call not executed

Here is the following code I have in Javascript:

document.getElementById("button").disabled = true;
document.getElementById("button").innerHTML = "Please Wait...";

var xhttp = new XMLHttpRequest();
xhttp.open("GET", "MoodInput"+ "?moodValue=" + input, false);
xhttp.send();

When I submit the form to the Servlet, it seems like the xhttp.send() function executes first. However, I would want the the following two lines to be executed first:

document.getElementById("button").disabled = true;
document.getElementById("button").innerHTML = "Please Wait...";

What should I do to solve the problem? It has to be synchronous, because there is a thread.sleep method in the servlet in order for the Arduino to be connected with the Serial Port and set up.

While a JavaScript function is running, browsers won't do very much at all, and that includes repainting the DOM.

Your code is running in the order you want, and the DOM is being updated, the page just isn't being repainted with the changes you made.

It has to be synchronous

Synchronous XMLHttpRequests are deprecated because they cause the browser to lock up while it waits for the response. ie because they cause the problem you are experiencing.

because there is a thread.sleep method in the servlet in order for the Arduino to be connected with the Serial Port and set up.

That will not be affected by using a synchronous or asynchronous request.

You are probably wanting to run some other JS that you left out of your question after the response has been received.

If so, the real solution is to take whatever it is you want to do after the request has completed and move it to a function that you assign as the XHR object's load event handler.

button input type="button" does not use innerHTML for the text it uses value :

document.getElementById("button").value = "Please Wait...";

Are you using an input or a button element?

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