首先要知道是么是 ajax
-> a 是 async (异步的)
-> j javascript
-> a and
-> xml (更加严格的html格式)
在html页面的ajax
const xhr = new XMLHttpRequest();
//可以将其打印出来,这个是一个对象。
//是专门用来创造实例对象来帮助你发送 ajax 请求的
// xhr.open('请求方式','请求的路径 (url)', 是否异步'true(异步)' false(同步) );
xhr.open('get', 'server.js',true);
xhr.onreadystatechange = function () {
if(xhr.readState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
// 这里拿到的是 [1,2,3,4];
// 这个就是 你拿到的数据;
}
}
xhr.send()
// 发送请求
在 nodejs 的代码
这里使用了一个 node 框架 express 目的是为了更加方便的搭建服务器
const express = require('express');
const path = require('path')
const app = express();
// 把 你写的 ajax 的 html文件挂起,这样子的话才不会跨域什么的。
app.get('/',(req,res) => {
res.sendFile(path.join(__dirname,'ajax.html'))
});
// 搭建服务器来挂起数据,这样的话才可以让 ajax 访问到。
app.get('/server',(req,res) => {
let data = [1,2,3,4];
// res.json(data); 两场方式都可以
res.send(data)
})
app.listen(3000,() => {
console.log("挂起页面 端口号 3000");
});
如何访问,在浏览器的 URL 地址栏填写 端口号。
欢迎大家来评论,体一些意见,如果有想看的评论我,我会的话我就发文章。