function SendHttpRequest(cmd, respondfunc){ var xhr = new XMLHttpRequest(); xhr.timeout = 3000; xhr.ontimeout = function (event) { alert("请求超时!"); } var urlStr = 'http://127.0.0.1:5000/' + cmd; console.log(urlStr); xhr.open('GET', urlStr); xhr.setRequestHeader('content-type', 'application/json'); xhr.onreadystatechange = function () { // console.log(xhr.readyState) // console.log(xhr.status) if (xhr.readyState == 4 && xhr.status == 200) { console.log('ok'); if(respondfunc != null){ respondfunc(xhr.responseText); } } else if(xhr.status == 200){ console.log('waiting'); } else { console.log('err'); console.log(xhr.status); } } xhr.send(null); }
时间: 2024-02-14 15:36:15 浏览: 41
这段代码是一个 JavaScript 函数,用于向指定的 URL 发送 HTTP GET 请求,并在请求响应后执行指定的回调函数。该函数的参数包括:
- cmd:指定要发送的请求命令;
- respondfunc:指定请求响应后要执行的回调函数。
该函数使用 XMLHttpRequest 对象实现请求发送和响应处理。在发送请求前,设置了请求超时时间为 3 秒,并指定超时处理函数为弹出超时提示。在发送请求时,设置了请求头部的 content-type 为 application/json。在响应处理函数中,判断响应状态为 200 时,执行指定的回调函数,并将响应文本作为参数传递给回调函数。如果响应状态为 200 以外的值,则输出错误信息和状态码。
相关问题
js XMLHttpRequest 设置timeout时间并监听timeout事件回调
在使用 XMLHttpRequest 进行 AJAX 请求时,可以通过设置 `timeout` 属性来指定超时时间(单位为毫秒),例如:
```javascript
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('请求失败');
}
}
};
xhr.open('GET', '/api/data', true);
xhr.timeout = 5000; // 设置超时时间为 5 秒
xhr.ontimeout = function() {
console.log('请求超时');
};
xhr.send();
```
在上面的代码中,我们通过设置 `xhr.timeout = 5000` 来将超时时间设置为 5 秒。同时,我们也通过 `xhr.ontimeout` 属性设置了超时事件的回调函数,在超时事件发生时会调用该函数。在上面的示例中,如果请求的响应时间超过 5 秒,就会触发 `xhr.ontimeout` 回调函数输出 "请求超时"。
XMLHttpRequest timeout怎么设置
XMLHttpRequest对象的timeout属性可以设置请求的超时时间,单位为毫秒。如果请求在超时时间内没有完成,将会触发XMLHttpRequest对象的ontimeout事件。下面是一个设置超时时间为5秒的示例代码:
```
var xhr = new XMLHttpRequest();
xhr.timeout = 5000; // 设置超时时间为5秒
xhr.ontimeout = function () {
console.log("请求超时!");
};
xhr.open("GET", "http://example.com/api", true); // 设置请求方式、URL和异步标识
xhr.send(); // 发送请求
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)