同步交互html
异步交互服务器
<body> <script src="chajian/createXMLHttpRequest.js"></script> <script> /* XMLHttpRequest对象 * XMLHttpRequest对象是Ajax的核心对象 * XMLHttpRequest对象是实现异步交互的核心 */ /* 经过createXMLHttpRequest()方法来建立一个XMLHttpRequest对象 */ var xhr = createXMLHttpRequest(); console.log( xhr );// 获得一个XMLHttpRequest对象 </script> </body>
建立XMLHttpRequest对象app
调用XMLHttpRequest对象的open()方法异步
open()方法学习
参数url
第一个参数 - 表示当前的请求方式code
调用XMLHttpRequest对象的send()方法orm
send()方法htm
参数对象
利用XMLHttpRequest对象的onreadystatechange事件
onreadystatechange事件
服务器端的通讯状态中 - 存在着处理完毕(信号)
readyState属性
属性值
responseText属性
将接收到的结果更新到HTML页面
<body> <button id="btn">按钮</button> <script src="chajian/createXMLHttpRequest.js"></script> <script> var btn = document.getElementById( 'btn' ); btn.addEventListener( 'click', function () { /* 实现Ajax异步交互 */ /* 1. 建立XMLHttpRequest对象 */ var xhr = createXMLHttpRequest(); /* 2. 调用XMLHttpRequest对象的open()方法 */ /* 经过open()方法来创建与服务器端的关系 */ xhr.open( 'get', 'http://localhost:63342/学习资料/XMLHttpRequest对象.html' ); /*3. 调用XMLHttpRequest对象的send()方法 */ /* 经过send()方法来向服务器端发送数据 */ xhr.send( null ); /* 4. 利用XMLHttpRequest对象的onreadystatechange事件 */ /* 设置onreadystatechange事件 */ xhr.onreadystatechange = function(){ /* 经过readyState属性来判断服务器端的状态 */ if (xhr.readyState === 4) { /* 经过responseText属性来获取服务器端的响应结果 */ console.log( xhr.responseText ); } } /* 5. 将接收到的结果更新到HTML页面 * 经过HTTP协议来完成 */ } ); </script> </body>
XMLHttpRequest对象的readyState属性
属性值
XMLHttpRequest对象的status属性
用于获得当前请求以后的响应状态码
属性值
responseText属性
responseXML属性
<body> <button id="btn">按钮</button> <script src="chajian/createXMLHttpRequest.js"></script> <script> var btn = document.getElementById( 'btn' ); btn.addEventListener( 'click', function(){ var xhr = createXMLHttpRequest(); xhr.onreadystatechange = function(){ /* 显示readyState属性 */ console.log( xhr.readyState ); /* 判断当前服务器端的状态 */ if ( xhr.readyState === 4 ) { /* 显示status属性 */ console.log( xhr.status ); /* 判断当前响应状态 */ if ( xhr.status === 200 ) { /* 显示responseText属性 */ console.log( xhr.responseText ); } } /* 能够同时判断当前服务器端的状态和响应状态 */ if ( xhr.readyState === 4 && xhr.status === 200 ) { /* 显示responseText属性 */ console.log( xhr.responseText ); } }; xhr.open( 'get', 'http://localhost:63342/学习资料/XMLHttpRequest对象.html' ); xhr.send( null ); } ); </script> </body>
XMLHttpRequest对象的send()方法
参数
send()方法的参数与当前的请求方式有关
若是当前的请求方式为 GET
send()方法中只能传递 null值
若是当前的请求方式为 POST
<body> <button id="btn">按钮</button> <script src="chajian/createXMLHttpRequest.js"></script> <script> var btn = document.getElementById( 'btn' ); btn.addEventListener( 'click',function(){ // 1.建立XMLHttpRequest对象 var xhr = createXMLHttpRequest(); xhr.onreadystatechange = function(){ if ( xhr.readyState === 4 && xhr.status === 200 ) { console.log( xhr.responseText ); } }; xhr.open( 'get', 'http://localhost:63342/学习资料/XMLHttpRequest对象.html' ); /* 设置请求头部信息 */ xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send( null ); } ); </script> </body>