当前位置: 首页 > 工具软件 > TimeOut > 使用案例 >

Ajax - timeout设置ajax请求超时 timeout

尉迟清野
2023-12-01

$.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>

 类似资料: