最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can we send a HTTP request synchronously? - Stack Overflow

programmeradmin0浏览0评论

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
 |  Show 1 more ment

1 Answer 1

Reset to default 5

The 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(); 
} 
发布评论

评论列表(0)

  1. 暂无评论