先准备好服务端代码,这里用express框架来构建服务端:
const express = require("express");
var bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.all('*', function (req, res, next) {
//设为指定的域
res.header('Access-Control-Allow-Origin', "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header('Access-Control-Allow-Credentials', true);
res.header("X-Powered-By", ' 3.2.1');
next();
});
app.get("/data", (req, res) => {
res.send("hello world");
});
app.get("/data/1", (req, res) => {
res.send("hello world1");
});
app.get("/data/2", (req, res) => {
res.send("hello world2");
});
app.get("/data/3", (req, res) => {
res.send("hello world3");
});
app.get('/data/books', (req, res) => {
res.send(req.query);
});
app.post('/data/comment', (req, res) => {
console.log(req.body);
res.send(req.body);
});
app.listen(3000, function () {
console.log('the server is running...');
});
普通的ajax请求,即通过XMLHTTPRequest对象来发送请求:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4) {
console.log(xhr.responseText);
}
};
xhr.open("get", "http://localhost:3000/data");
xhr.send(null);
通过jquery的ajax方法来发送请求:
$.ajax({
url: "http://localhost:3000/data",
type: "get",
success: function(data){
console.log(data);
}
});
上面的两种方法虽然能发送异步请求得到相应结果,如果发送多个异步请求则无法保证得到的响应的顺序,因此只能不断的嵌套,如:
$.ajax({
url: "http://localhost:3000/data/1",
type: "get",
success: function(data){
console.log(data);
$.ajax({
url: "http://localhost:3000/data/2",
type: "get",
success: function(data){
console.log(data);
}
});
}
});
为了解决这种情况,可以使用Promise语法。
使用Promise来处理回调:
function ajax(url){
return new Promise(function (resolve, reject) {
$.ajax({
url: url,
type: "get",
success: function(data){
resolve(data);
},
error: function(error) {
reject(error);
}
});
});
}
ajax("http://localhost:3000/data/1").then(function(data){
console.log(data);
return ajax("http://localhost:3000/data/2");
}).then(function (data) {
console.log(data);
return ajax("http://localhost:3000/data/34");
}).then(function(data){
console.log(data);
}).catch(function(err){
console.log('err');
}).finally(function(){
console.log('我一定会执行');
});
上面首先定义了一个函数ajax,其参数为要请求的url,这个函数返回一个Promise对象,在Promise对象中处理异步请求,如果请求成功,则调用resolve方法,否则调用reject方法。之后就可以调用该函数,该函数返回的Promise对象可以调用then方法,该方法可以传入一个函数,对应着Promise的resolve,其形参data即请求得到的数据。之后如果想要继续发送异步请求,则可以返回ajax函数,即返回一个新的Promise对象,之后就可以继续用then来获取数据。通过这种方法可以链式编程,从而避免代码的嵌套问题。代码中的catch函数可以捕获Promise中的错误,而finally函数则必定会执行。
Promise还有两个方法,一个是Promise.all(),另一个是Promise.race():
function ajax(url){
return new Promise(function (resolve, reject) {
$.ajax({
url: url,
type: "get",
success: function(data){
resolve(data);
},
error: function(error) {
reject(error);
}
});
});
}
var p1 = ajax("http://localhost:3000/data/1");
var p2 = ajax("http://localhost:3000/data/2");
var p3 = ajax("http://localhost:3000/data/3");
Promise.all([p1,p2,p3]).then(function(result){
console.log(result);
});
Promise.race([p1,p2,p3]).then(function(data){
console.log(data);
});
Promise.all()接受一个数组,数组中存储着Promise对象,数组中的Promise对象都会执行then。then()的形参result是一个数组,分别是三个Promise的响应。而Promise.race()也是接受一个数组,但是只会执行其中一个Promise对象,故then()的形参data就是响应最快的那个Promise的响应。
使用fetch API来发送请求。
(1)发送GET请求
fetch("http://localhost:3000/data",{ method: "get"}).then((data) => {
return data.text();
}).then((data)=>{
console.log(data);
})