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-Com
·
$.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事件:ontimeout
xhr.ontimeout = function(err) {
console.log(err)
}
xhr.send()
xhr.onload = function() {
console.log(xhr.responseText)
}
}
</script>
</body>
</html>
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)