If I am correct, "A" in "AJAX" means sending a HTTP request asynchronously without waiting for a HTTP response.
I learn that we can send an asynchronous HTTP request by XMLHttpRequest
, for example:
function handleButtonPress(e) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = handleResponse;
httpRequest.open("GET", e.target.innerHTML + ".html");
httpRequest.send();
}
How can we send a HTTP request synchronously?
If I am correct, "A" in "AJAX" means sending a HTTP request asynchronously without waiting for a HTTP response.
I learn that we can send an asynchronous HTTP request by XMLHttpRequest
, for example:
function handleButtonPress(e) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = handleResponse;
httpRequest.open("GET", e.target.innerHTML + ".html");
httpRequest.send();
}
How can we send a HTTP request synchronously?
Share Improve this question edited Jun 25, 2019 at 21:09 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked May 3, 2019 at 10:39 TimTim 99.9k148 gold badges402 silver badges640 bronze badges 6- What use case do you have for synchronous requests? In general they are not remended (certain browsers even state this in their console when a synchronous request is sent) – NielsNet Commented May 3, 2019 at 10:42
-
Just put
false
as the 3rd parameter to open, but a big warning, if you use this feature not inside a WebWorker it might stop working in the future. – Keith Commented May 3, 2019 at 10:42 - I suppose the question is more about alternatives to XMLHttpRequest, no? – raina77ow Commented May 3, 2019 at 10:43
- Possible duplicate of JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..." – Jorge Fuentes González Commented May 3, 2019 at 10:46
- @Keith Thanks. where do you remend to look up the API usages? – Tim Commented May 3, 2019 at 11:18
1 Answer
Reset to default 5The third param in open function is for async request sending. You can set it to false for a synchronous request
function handleButtonPress(e) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = handleResponse;
httpRequest.open("GET", e.target.innerHTML + ".html", false);
httpRequest.send();
}