html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>原生ajax封装</title>
</head>
<body>
<button onclick="get()">get</button>
<button onclick="post()">post</button>
<script type="text/javascript">
function ajax(options = {}) {
options.type = (options.type || "GET").toUpperCase(); // 请求类型
options.dataType = options.dataType || "json"; // 返回值类型
options.async = options.async || true; // 是否异步请求
var params = "";
if(options.data) { // 格式化参数
var arr=[];
for(var name in options.data){
arr.push(encodeURIComponent(name)+"="+encodeURIComponent(options.data[name]));
}
arr.push(("v="+Math.random()).replace(".",""));
params = arr.join("&");
}
var xhr; // 创建请求实例
if(window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}else if(window.ActiveXObject) { // 兼容老版本IE
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
// 区分GET||POST
if(options.type === "GET") {
xhr.open(options.type, `${options.url}?${params}`, options.async);
xhr.send(null);
}else {
xhr.open(options.type, `${options.url}`, options.async);
if(options.header) { // 设置请求头
for(var key in options.header) {
console.log(key, options.header[key])
xhr.setRequestHeader(key, options.header[key]);
}
}
console.log(params)
xhr.send(params);
}
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
if(xhr.status === 200) {
options.success(JSON.parse(xhr.responseText))
}else {
options.fail(xhr.responseText)
}
options.complete();
}
}
}
function get() {
ajax({
type: "GET",
url: "http://localhost:3001/user",
data: {
userId: '123456'
},
success(res) {
console.log(res)
},
fail(err) {
console.log(err)
},
complete() {
console.log(1111)
}
})
}
function post() {
ajax({
type: "POST",
url: "http://localhost:3001/setUser",
header: {
"Content-type": "application/x-www-form-urlencoded"
},
data: {
userId: "123456",
name: "李四",
age: 108
},
success(res) {
console.log(res)
},
fail(err) {
console.log(err)
}
})
}
</script>
</body>
</html>
服务端(方便测试, 简写)
const Koa = require("koa");
const bobyParser = require("koa-bodyparser");
const router = require("koa-router")();
const app = new Koa();
app.use(async (ctx, next) => {
ctx.set('Access-Control-Allow-Origin', '*');
ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
if (ctx.method == 'OPTIONS') {
ctx.body = 200;
} else {
await next();
}
})
router.get("/user", async (ctx) => {
let data = ctx.request.query;
if(data.userId === '123456') {
ctx.body = {
status: 200,
message: "请求成功",
data: {
name: "张三",
age: 12
}
}
}else {
ctx.body = {
status: 400,
message: "数据查询失败"
}
}
})
router.post("/setUser", async (ctx) => {
let data = ctx.request.body;
ctx.body = {
data
}
console.log(data)
})
app.listen("3001", () => {
console.log("app服务已启动 3001")
})
app.use(bobyParser());
app.use(router.routes());