企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
* [1.http请求](https://www.kancloud.cn/chengbenchao/javascript/780058#1http_1) * [2.请求响应](https://www.kancloud.cn/chengbenchao/javascript/780058#2_8) * [3.一个完整的ajax的步骤](https://www.kancloud.cn/chengbenchao/javascript/780058#3ajax_13) * [1.创建](https://www.kancloud.cn/chengbenchao/javascript/780058#1ajax_14)[ajax核心](https://www.kancloud.cn/chengbenchao/javascript/780058)对象 * [2.与服务器建立](https://www.kancloud.cn/chengbenchao/javascript/780058#2_15)[连接](https://www.kancloud.cn/chengbenchao/javascript/780058) * [3.发送](https://www.kancloud.cn/chengbenchao/javascript/780058#3_16)[请求](https://www.kancloud.cn/chengbenchao/javascript/780058) * [4.响应](https://www.kancloud.cn/chengbenchao/javascript/780058#4_17) * [get请求](https://www.kancloud.cn/chengbenchao/javascript/780058#get_18) * [post请求](https://www.kancloud.cn/chengbenchao/javascript/780058#post_38) * [Post方式要设置一个](https://www.kancloud.cn/chengbenchao/javascript/780058#Post_39)[请求头](https://www.kancloud.cn/chengbenchao/javascript/780058) ## 1.http请求 > 定义:http计算机通过网络进行通信的规则 > ![](https://box.kancloud.cn/4b3f4191f299bb5da204ba2068e06f13_633x403.png) > ![](https://box.kancloud.cn/5270eec3ea4ba4f62af01112ea5b1da3_753x299.png) > ![](https://box.kancloud.cn/744c00043585906db046b0f520d1b195_762x258.png) > ![](https://box.kancloud.cn/28b71b4a5bdf8c5a1443818bf0116b15_741x242.png) > ![](https://box.kancloud.cn/513735421f4d819d4dcf1561e3d5a10d_703x297.png) ## 2.请求响应 * open(method,url,asyn) asyn值默认为true * send() * onreadystatechange ## 3.一个完整的ajax的步骤 #### 1.创建[ajax核心](https://www.kancloud.cn/chengbenchao/javascript/780058)对象 #### 2.与服务器建立[连接](https://www.kancloud.cn/chengbenchao/javascript/780058) #### 3.发送[请求](https://www.kancloud.cn/chengbenchao/javascript/780058) #### 4.响应 ### get请求 ~~~ var url = "https://www.easy-mock.com/mock/5bac6df10132334db7167178/testDemo/testDemo"; var xhr = new XMLHttpRequest(); xhr.open('get',url,true); xhr.send(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ var txt = JSON.parse(xhr.responseText); console.log(txt); } } ~~~ JSON.parse()方法将json对象解析为JavaScript对象。 JSON.stringify()将javascript的值,转换为JSON字符串。 * responseText:获取字符串形式的响应数据 * status:以数字形式返回http的状态码 * readystate值代表服务器响应的变化 ![](https://box.kancloud.cn/55be8b52b6916319a3852475c056f77f_718x354.png) ### post请求 #### Post方式要设置一个[请求头](https://www.kancloud.cn/chengbenchao/javascript/780058) ~~~ <div id="test"></div> <script> var test = document.getElementById("test"); var xhr = new XMLHttpRequest(); xhr.open("post","https://www.easy-mock.com/mock/5b230e1e6bed703a9b488c69/www.getTest.com/push",true); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(null); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ var data = JSON.parse(xhr.responseText); test.innerHTML = data.data.content } } </script> ~~~