1、创建服务器
在server目录中下载Express框架,并新建app.js,编写JavaScript代码。
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();
});
// express.static()中间件用来设置静态文件public目录
app.use(express.static(path.join(__dirname, 'public')));
// 定义/first路由
app.get('/first', (req, res) => {
res.send('Hello,Ajax');
});
app.listen(3000);
console.log('服务器启动成功');
获取服务器端的响应
onload事件
通过onload事件的方式获取服务器端响应到客户端的数据。
基本语法格式:
xhr.onload = function () {};
xhr
表示Ajax对象,onload
属性的值为事件处理函数。
onreadystatechange事件
通过onreadystatechange事件的方式获取服务器端响应到客户端的数据。
基本语法格式:
xhr.onreadystatechange = function () {};
xhr表示Ajax对象,onreadystatechange属性的值是事件处理函数。
2、配置Ajax对象
使用open()
方法来配置Ajax对象,最后使用send()
方法发送请求。
基本语法格式:
var xhr = new XMLHttpRequest();
xhr.open('请求方式', '请求地址');
xhr.send();
在server\public目录下新建demo.html文件,编写JavaScript代码。
<script>
var xhr = new XMLHttpRequest();
console.log(xhr.readyState); // 获取Ajax状态码0
xhr.open('get','http://localhost:3000/first');
console.log(xhr.readyState); // 获取Ajax状态码1
</script>
3、发送请求
监听onload事件,并使用send()方法发送请求。
在demo.html文件中,编写JavaScript代码。
xhr.onload = function () {
console.log(xhr.readyState); // 获取Ajax状态码4
console.log(xhr.responseText); // 输出“Hello, Ajax”
};
xhr.send();
完整demo.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>Ajax</title>
</head>
<body>
<script>
var xhr = new XMLHttpRequest();
console.log(xhr.readyState); // 获取Ajax状态码0
xhr.open('get', 'http://localhost:3000/first');
console.log(xhr.readyState); // 获取Ajax状态码1
xhr.onload = function () {
console.log(xhr.readyState); // 获取Ajax状态码4
console.log(xhr.responseText); // 输出“Hello, Ajax”
};
xhr.send();
</script>
</body>
</html>
使用node app.js命令启动服务器,然后打开demo.html,查看控制台中的输出结果。
0表示创建了Ajax对象;
1表示调用open()方法已经对Ajax对象进行了配置
4表示服务器端的响应数据已经接收完成,触发事件处理函数。
将onload事件修改为onreadystatechange事件
修改demo01.html文件,编写如下代码。
xhr.onreadystatechange = function () {
console.log(xhr.readyState); // 获取Ajax状态码2 3 4
// 对Ajax状态码进行判断 如果状态码的值为4就代表数据已经接收完成了
if (xhr.readyState === 4) {
console.log(xhr.responseText); // 输出Hello, Ajax
}
}
xhr.send();
使用node app.js命令启动服务器,然后打开demo.html,查看控制台中的输出结果。
0表示创建了Ajax对象;
1表示调用open()方法已经对Ajax对象进行了配置
2表示请求已经发送了但是还没有接收到服务器端响应的数据;
3表示已经接收到服务器端的部分数据了;
4表示服务器端的响应数据接收完成了,触发事件处理函数。