ajax()封装
封装ajax()函数的参数对象,包括type请求方式、url请求地址、date请求数据、async异步or同步、success请求成功后处理请求结果的函数。
<!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>
<script>
function ajax(options) {
var params = formsParams(options.data);
//创建对象
var xhr = new XMLHttpRequest()
// 连接
if (options.type == "GET") {
xhr.open(options.type, options.url + "?" + params, options.async);
xhr.send()
} else if (options.type == "POST") {
xhr.open(options.type, options.url, options.async);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(params);
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
options.success(xhr.responseText);
}
}
function formsParams(data) {//处理数据
var arr = [];
for (var prop in data) {
arr.push(prop + "=" + data[prop]);
}
return arr.join("&");
}
}
ajax({
url: "http://localhost:3000/get", // url:地址
type: "GET", // type : 请求方式
async: true, // async: 同步:false,异步:true
data: { //传入信息
name: "张三",
age: 18
},
success: function (data) { //返回接受信息
console.log(data);
}
})
</script>
</body>
</html>
服务器部分
这个服务器是一个get请求方式的,如需要post的请求方式则将二级路由的/get
改为/post
。
const express = require('express');
const path = require('path');
const app = express();
app.all('*', function(req, res, next) {//处理跨域问题
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers',['mytoken','Content-Type'])
next();
});
app.use(express.static(path.join(__dirname, 'public')));
// 定义GET路由
app.get('/get', (req, res) => {
res.send(req.query);
});
app.listen(3000);
console.log('服务器启动成功');
JQuery中的Ajax
jQuery 对 XMLHttpRequest 进行了封装,提供了一系列 Ajax 相关的函数,极大地降低了 Ajax 的使用难度。
$.get()
JQuery中$.get()方法专门发送get请求,将服务器上的资源请求到客户端使用。
基本语法格式:
$.get(url,[data],[callback]);
●url:[string]必须按参数,要请求的资源地址。
●data:[object]可选参数,请求数据。
●callback:[function]可选参数,请求成功后的回调函数。
不带参数的get请求
$.get('url',function (res) {
console.log(res)
})
带参数的get请求
$.get('url',function (res),{参数名:参数值} {
console.log(res)
})
$.post()
JQuery中$.post()方法专门发送post请求,将服务器上的资源请求到客户端使用。
基本语法格式:
$.post(url,[data],[callback]);
●url:[string]必须按参数,要请求的资源地址。
●data:[object]可选参数,请求数据。
●callback:[function]可选参数,请求成功后的回调函数。
不带参数的post请求
$.post('url',function (res) {
console.log(res)
})
带参数的post请求
$.post('url',function (res),{参数名:参数值} {
console.log(res)
})
$.ajax()
jQuery 中提供的 $.ajax() 函数,是一个功能比较综合的函数,它允许我们对 Ajax 请求进行配置,从而响应不同的请求方式。其用法和ajax()相似。
$.ajax({
type: '',
url: '',
data: {},
success: function(res) {}
})
●type: 请求的方式,例如 GET 或 POST。
●url: 请求的 URL 地址。
●data: {} 这次请求要携带的数据。
●success: function(res) {}请求成功之后的回调函数。