简介 :
全称 | Ajax(Asynchronous Javascript And XML) |
作用 | 1.不需要刷新页面即更新内容 2.浏览器和服务器之间的一种通信方式 |
常用参数 :
XMLHttpRequest | 一个构造函数,用于实现浏览器与服务器之间的异步通信 例子:let xhr=new XMLHttpRequest() | ||||||||||
readyState | 表示XMLHttpRequest的状态
| ||||||||||
response | 获得任意类型的响应数据 | ||||||||||
responseText | 获得字符串类型的响应数据 | ||||||||||
responseType | 设置响应数据的类型 | ||||||||||
timeout | 设置请求超时时间,单位是ms | ||||||||||
status | 表示HTTP状态码,200 网页...ok | ||||||||||
statusText | 表示HTTP状态码说明 | ||||||||||
withCredentials | 指定使用ajax发送请求时,是否携带cookie | ||||||||||
open | 设置请求的类型,URL以及是否异步处理请求 | ||||||||||
send | 发送请求 | ||||||||||
abort | 终止当前的请求 | ||||||||||
setRequestHeader | 设置请求头信息,其中Content-type字段告诉服务器,数据格式 设置发送的数据是-表单默认的提交数据的格式: 例子:xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded') | ||||||||||
onreadystatechange | 当readyState改变时,就会触发onreadystatechange事件 |
代码示例 :
浏览器与服务器之间,进行简单的通信
前端文件 :index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>Ajax交互</h1>
<button id="bt_get">Get测试</button>
<button id="bt_post">Post测试</button>
<script>
const bt_get = document.getElementById("bt_get");
const bt_post = document.getElementById("bt_post");
var jx = {
type: "POST",
url: "http://127.0.0.1:80/",
data: { name: "abc", move: "电影" },
dataType: "json",
async: true,
success: function () {
console.log("is ok...");
},
error: function () {
alert("Error:非POST或GET请求");
},
};
function paramGroup(data) {
let arr = [];
for (let i in data) {
arr.push(i + "=" + data[i]);
}
return arr.join("&");
}
function ajaxFc(obj) {
var xhr = null,
str = paramGroup(obj.data);
// 创建xhr
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft,XMLHTTP");
}
console.log(obj.type.toLowerCase());
if (obj.type.toLowerCase() === "get" && obj.data !== undefined) {
let url = obj.url + "?" + str;
xhr.open(obj.type, url, obj.async || true);
xhr.send(null);
} else if (
obj.type.toLowerCase() === "post" &&
obj.data !== undefined
) {
xhr.open(obj.type, obj.url, obj.async || true);
xhr.setRequestHeader(
"Content-type",
"application/x-www-form-urlencoded"
);
xhr.send(str);
} else {
obj.error();
return false;
}
// 事件绑定 处理服务端返回的结果
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
let res = xhr.responseText;
try {
if (typeof res === "object" || typeof res === "string") {
alert(res);
} else if (obj.dataType === "json") {
console.log("json数据");
} else {
throw new Error();
}
} catch (e) {
throw new Error();
}
}
};
}
bt_get.onclick = function () {
jx.type = "get";
jx.url = "http://127.0.0.1:80/api/get";
ajaxFc(jx);
};
bt_post.onclick = function () {
jx.type = "post";
jx.url = "http://127.0.0.1:80/api/post";
ajaxFc(jx);
};
</script>
</body>
</html>
后端文件 :index.js
const express = require('express');
const e = express();
e.get('/api/get', (req, res) => {
res.send('Get ....Ok');
});
e.post('/api/post', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.send('Post ....Ok');
});
e.listen(80, function () {
console.log('Server runing at 127:0.0.1:80');
});
代码运行