1、express创建node服务端
首先ajax的作用是从网页从服务端获取数据的一个东西。
说到服务端,得提一个库包:express
利用express创建node服务器
// 创建node服务器
// 导入express
const express = require('express')
// 创建web服务器,把express放在app实例上
const app = express()
//注册全局
app.use()
//使用app.listen方法启动服务器,listen是最后
app.listen(80,()=>{
console.log('服务器启动成功');
})
服务器端创建对于各种请求类型的回馈函数
//第一个参数为url地址,第二个为函数。
app.get()
App.post(url,(request,response)=>{})
这是ajax里面最基本的服务器端。
2、ajax创建对象链接服务器端
//1.创建对象
const xhr = new XMLHttpRequest();
//2.初始化xhr对象
Xor.open(‘POST/GET…’,’url’);
//3.发送请求,在这里,可以传请求体参数
xhr.send();
//4.事件绑定 处理服务器端返回的结果
//on when
//readystate是xhr对象中的属性,表示状态
//0未初始化,刚开始
//1表示open调用完毕,2表示send方法调用完毕
//3表示服务端返回部分结果,4表示返回全部结果
xhr.onreadystatechange = function(){
//判断服务器已经返回了所有结果
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status<300){
//处理结果 行 头 空行 体
console.log(xhr.status);//响应状态码
console.log(xhr.statusText);//状态字符串
console.log(xhr.getAllResponseHeaders);//所有响应头
console.log(xhr.response);//响应体
}
}
}
最简单的ajax对象链接服务器代码。