简体   繁体   English

未执行AJAX / XMLHttpRequest调用之前的代码行

[英]Lines of code before AJAX/XMLHttpRequest Call not executed

Here is the following code I have in Javascript: 这是我在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. 当我将表单提交到Servlet时,似乎首先执行xhttp.send()函数。 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. 它必须是同步的,因为servlet中有一个thread.sleep方法,以便Arduino与Serial Port连接并进行设置。

While a JavaScript function is running, browsers won't do very much at all, and that includes repainting the DOM. 当JavaScript函数运行时,浏览器根本不会做很多事情,这包括重新绘制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. 您的代码按照您想要的顺序运行,并且DOM正在更新,只是页面没有被所做的更改重新绘制。

It has to be synchronous 它必须是同步的

Synchronous XMLHttpRequests are deprecated because they cause the browser to lock up while it waits for the response. 不建议使用同步XMLHttpRequest,因为它们会导致浏览器在等待响应时锁定。 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. 因为servlet中有一个thread.sleep方法,以便Arduino与串行端口连接并进行设置。

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. 您可能希望在收到响应运行其他一些您在问题中遗漏的JS

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. 如果是这样,真正的解决方案是在请求完成后采取您想做的所有事情,然后将其移至您指定为XHR对象的装入事件处理程序的函数。

button input type="button" does not use innerHTML for the text it uses value : button input type="button"不使用innerHTML作为它使用value的文本:

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

Are you using an input or a button element? 您正在使用输入或按钮元素吗?

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

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