diff --git "a/53 \345\221\250\345\216\232\350\276\260/2023-12-06 \347\254\254\344\272\214\345\215\201\346\254\241\344\275\234\344\270\232 Ajcx.md" "b/53 \345\221\250\345\216\232\350\276\260/2023-12-06 \347\254\254\344\272\214\345\215\201\346\254\241\344\275\234\344\270\232 Ajcx.md" new file mode 100644 index 0000000000000000000000000000000000000000..1218fdb7d2d5fda3e1622056620611ea523e5f28 --- /dev/null +++ "b/53 \345\221\250\345\216\232\350\276\260/2023-12-06 \347\254\254\344\272\214\345\215\201\346\254\241\344\275\234\344\270\232 Ajcx.md" @@ -0,0 +1,85 @@ +ajax + +````js +1) 创建 XMLHttpRequest 对象 +var xhr = new XMLHttpRequest(); +2) 设置请求信息 +xhr.open(method, url); +//可以设置请求头,一般不设置 +xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); +3) 发送请求 +xhr.send(body) //get 请求不传 body 参数,只有 post 请求使用 +4) 接收响应 +//xhr.responseXML 接收 xml 格式的响应数据 +//xhr.responseText 接收文本格式的响应数据 +xhr.onreadystatechange = function (){ +if(xhr.readyState == 4 && xhr.status == 200){ +var text = xhr.responseText; +console.log(text); +}} +``` + +### 1.1 Get方式 + +```js +//绑定事件 + btn.onclick = function () { + //1. 创建对象 + const xhr = new XMLHttpRequest(); + //2. 初始化 设置请求方法和 url + xhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200&c=300'); + //3. 发送 + xhr.send(); + //4. 事件绑定 处理服务端返回的结果 + // on when 当....时候 + // readystate 是 xhr 对象中的属性, 表示状态 0 1 2 3 4 + // change 改变 + xhr.onreadystatechange = function () { + //判断 (服务端返回了所有的结果) + if (xhr.readyState === 4) { + //判断响应状态码 200 404 403 401 500 + // 2xx 成功 + if (xhr.status >= 200 && xhr.status < 300) { + //处理结果 行 头 空行 体 + //响应 + // console.log(xhr.status);//状态码 + // console.log(xhr.statusText);//状态字符串 + // console.log(xhr.getAllResponseHeaders());//所有响应头 + // console.log(xhr.response);//响应体 + //设置 result 的文本 + result.innerHTML = xhr.response; + } else {} + } + } + } +``` + +### 1.2 Post方式 + +```js +//绑定事件 + result.addEventListener("mouseover", function(){ + //1. 创建对象 + const xhr = new XMLHttpRequest(); + //2. 初始化 设置类型与 URL + xhr.open('POST', 'http://127.0.0.1:8000/server'); + //设置请求头 + xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); + xhr.setRequestHeader('name','aodi'); + //3. 发送 + xhr.send('a=100&b=200&c=300'); + // xhr.send('a:100&b:200&c:300'); + // xhr.send('1233211234567'); + //4. 事件绑定 + xhr.onreadystatechange = function(){ + //判断 + if(xhr.readyState === 4){ + if(xhr.status >= 200 && xhr.status < 300){ + //处理服务端返回的结果 + result.innerHTML = xhr.response; + } + } + } + }); +```` +