企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## AJAX - 创建XMLHttpRequest对象  XMLHttpRequest 是 AJAX 的基础。  XMLHttpRequest 术语缩写为XHR,中文可以解释为可扩展超文本传输请求。  XMLHttpRequest 对象可以在不向服务器提交整个页面的情况下,实现局部更新网页。  XMLHttpRequest的对象用于客户端和服务器之间的异步通信。  它执行以下操作: 1. 在后台从客户端发送数据 2. 从服务器接收数据 3. 更新网页而不重新加载。 ## XMLHttpRequest 对象  所有现代浏览器均支持 XMLHttpRequest 对象(IE5 和 IE6 使用 ActiveXObject)。  XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。 ## 创建 XMLHttpRequest 对象 * * *  所有现代浏览器(IE7+、Firefox、Chrome、Safari 以及 Opera)均内建 XMLHttpRequest 对象。  创建 XMLHttpRequest 对象的语法: ~~~ variable=new XMLHttpRequest(); ~~~  老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象: ~~~ variable=new ActiveXObject("Microsoft.XMLHTTP"); ~~~  为了应对所有的现代浏览器,包括 IE5 和 IE6,请检查浏览器是否支持 XMLHttpRequest 对象。如果支持,则创建 XMLHttpRequest 对象。如果不支持,则创建 ActiveXObject :: ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Tryrun 1</title> </head> <body> <div id="view"> <p>点击下面的按钮,将 Ajax 请求回来的数据更新在该文本内</p> </div> <button type="button" id="btn">发起 Ajax 请求</button> <script> document.getElementById("btn").onclick = ajaxRequest; function ajaxRequest () { var xhr = new XMLHttpRequest(); xhr.open("GET", "https://www.w3cschool.cn/statics/demosource/ajax_info.txt", true); xhr.send(); xhr.onreadystatechange = function(){ if (xhr.readyState === 4 && xhr.status === 200) { document.getElementById("view").innerHTML = xhr.responseText; } } } </script> </body> ``` ## XMLHttpRequest对象的属性 XMLHttpRequest对象的常见属性如下: | 属性| 描述 | | --- | --- | | onreadystatechange| 存储函数(或函数名),每当readyState的属性改变时,就会调用该函数。| | readyState | 存有的XMLHttpRequest的状态从0到4发生变化。 0:请求未初始化 ;1:服务器连接已建立 ; 2:请求已接收 ; 3:请求处理中; 4:请求已完成,且响应已就绪 | | reponseText | 以文本形式返回响应。 | | responseXML| 以XML格式返回响应 | | status | 将状态返回为数字(例如,“Not Found”为404,“OK”为200) | | statusText | 以字符串形式返回状态(例如,“Not Found”或“OK”) | ### XMLHttpRequest对象的方法 XMLHttpRequest对象的重要方法如下: | 方法 | 描述 | | --- | --- | | abort() | 取消当前请求 | | getAllResponseHeaders() | 以字符串形式返回完整的HTTP标头集。 | | getResponseHeader( headerName ) | 返回指定HTTP标头的值。 | | void open(method,URL) | 打开指定获取或交的方法和URL的请求。 | | void open(method,URL,async) |与上面相同,但指定异步或不。 | | void open(method,URL,async,userName,password) | 与上面相同,但指定用户名和密码。 | | void send(content) | 发送获取请求。 | | setRequestHeader( label,value) | 将标签/值对添加到要发送的HTTP标头。 |