1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > Ajax - timeout设置ajax请求超时 timeout

Ajax - timeout设置ajax请求超时 timeout

时间:2021-03-29 02:12:03

相关推荐

Ajax - timeout设置ajax请求超时 timeout

$.ajax实现

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta http-equiv="X-UA-Compatible" content="ie=edge" /><title>Document</title><script src="./libs/jquery/jquery.js"></script></head><body><button>发起请求</button><script>document.querySelector('button').onclick = function() {$.ajax({url: 'http://127.0.0.1:3001/getStudentsJSONDelay',// 通过timeout属性设置超时,单位是毫秒timeout: 2000,// 超时会认为请求失败,在ajax中会触发error事件error: function(err) {console.log(err)},success: function(res) {console.log(res)}})}</script></body></html>

原生实现

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta http-equiv="X-UA-Compatible" content="ie=edge" /><title>Document</title></head><body><button>发起请求</button><script>document.querySelector('button').onclick = function() {let xhr = new XMLHttpRequest()xhr.open('get', 'http://127.0.0.1:3001/getStudentsJSONDelay')// 设置超时,如果服务器响应的时间超出了指定时间,浏览器就会认为本次请求失败xhr.timeout = 2000// 失败的请求会触发timeout事件:ontimeoutxhr.ontimeout = function(err) {console.log(err)}xhr.send()xhr.onload = function() {console.log(xhr.responseText)}}</script></body></html>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。