XMLHttpRequest.open

深藏阁楼爱情的钟 2022-03-08 07:52 251阅读 0赞

XMLHttpRequest.open()方法用于指定 HTTP 请求的参数,或者说初始化 XMLHttpRequest 实例对象。它一共可以接受五个参数。

  1. void open(
  2. string method,
  3. string url,
  4. optional boolean async,
  5. optional string user,
  6. optional string password
  7. );
  • method:表示 HTTP 动词方法,比如GETPOSTPUTDELETEHEAD等。
  • url: 表示请求发送目标 URL。
  • async: 布尔值,表示请求是否为异步,默认为true。如果设为false,则send()方法只有等到收到服务器返回了结果,才会进行下一步操作。该参数可选。由于同步 AJAX 请求会造成浏览器失去响应,许多浏览器已经禁止在主线程使用,只允许 Worker 里面使用。所以,这个参数轻易不应该设为false。
  • user:表示用于认证的用户名,默认为空字符串。该参数可选。
  • password:表示用于认证的密码,默认为空字符串。该参数可选。

注意,如果对使用过open()方法的 AJAX 请求,再次使用这个方法,等同于调用abort(),即终止请求。

下面发送 POST 请求的例子。

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>XMLHttpRequest Open</title>
  6. </head>
  7. <body>
  8. <script> var xhr = new XMLHttpRequest(); xhr.onloadstart = function (e) { console.log('onloadstart'); }; xhr.onload = function (e) { console.log('onload'); }; xhr.onerror = function (e) { console.log('error'); }; xhr.onabort = function (e) { console.log('onabort'); }; xhr.onloadend = function (e) { console.log('onloadend'); }; xhr.onreadystatechange = function (e) { console.log(e, xhr.readyState, xhr.status); if (xhr.readyState == 4) { if (xhr.status == 200) { console.log('success'); } } }; xhr.open("POST", "http://192.168.38.79:8080"); xhr.send(); //注意,如果对使用过open()方法的 AJAX 请求,再次使用这个 open() 方法,等同于调用abort(),即终止请求,但onabort事件不会触发。 xhr.open("POST", "http://192.168.38.79:8080"); </script>
  9. </body>
  10. </html>

发表评论

表情:
评论列表 (有 0 条评论,251人围观)

还没有评论,来说两句吧...

相关阅读