AJAX是什么
AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。
通过AJAX可以在浏览器中向服务器发送异步请求。
AJAX 不是新的编程语言,而是一种使用现有标准的新方法。
为什么要用AJAX
优点
- 不刷新页面更新网页
- 在页面加载后从服务器请求数据
- 在页面加载后从服务器接收数据
- 在后台向服务器发送数据
缺点
- 没有浏览历史,不能回退
- 存在跨域问题(同源)
- SEO不友好
AJAX示例
原生
// 1. 创建对象
const xhr = new XMLHttpRequest();
// (可选)超时设置 2s 设置
xhr.timeout = 2000;
// (可选)超时回调
xhr.ontimeout = function ()
{
alert("网络异常,请稍后重试!!");
}
// (可选)网络异常回调
xhr.onerror = function ()
{
alert("你的网络似乎除了一些问题!");
}
// (可选)设置响应体数据的类型,默认为字符串
xhr.responseType = "json";
// 2. 初始化 设置请求方法和 url
xhr.open("GET", "http://127.0.0.1:8000/json-server")
// (可选)设置请求头
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.setRequestHeader("name", "welllin");
// 3. 发送
xhr.send();
//xhr.send("a=100&b=200&c=300"); // POST请求方法发送请求体的方法1
//xhr.send("a:100&b:200&c:300"); // POST请求方法发送请求体的方法2
// 4. 事件绑定 处理服务端返回的结果
xhr.onreadystatechange = function()
{
// readystate 是 xhr 对象中的属性,表示状态 0 1 2 3 4
// 0: 未初始化;1: 已调用open方法;2: 已调用send方法
// 3: 服务器端已返回部分结果;4: 服务器端已返回所有结果
if(xhr.readyState == 4)
{
// 判断响应状态码 xhr.status 200 404 403 401 500
// 2xx 表示成功
if(xhr.status >= 200 && xhr.status < 300)
{
// 处理结果 行 头 空行 体
//响应行
console.log(xhr.status); //状态码
console.log(xhr.statusText); //状态字符串
console.log(xhr.getAllResponseHeaders()); //所有响应头
console.log(xhr.response); //响应体
//x.abort(); // 取消请求
}
}
}
jQuery
$('button').eq(0).click(function()
{
$.get('http://127.0.0.1:8000/jquery-server', {a:100, b:200}, function(data){
console.log(data);
},"json")
})
$('button').eq(1).click(function()
{
$.post('http://127.0.0.1:8000/jquery-server', { a: 100, b: 200 }, function (data){
console.log(data);
})
})
$('button').eq(2).click(function ()
{
$.ajax({
//url
url: "http://127.0.0.1:8000/jquery-server",
//参数
data: {a:100, b:200},
// 请求类型
type: "GET",
// 响应体结果
dataType: "json",
// 成功的回调
success: function (data) {
console.log(data);
},
// 超时时间
timeout: 2000,
// 失败的回调
error: function (){
console.log("出错啦!!");
},
// 头信息
headers:{
c:300,
d:400
}
});
});
fetch
const btn = document.querySelector('button');
btn.onclick = function()
{
fetch("http://127.0.0.1:8000/fetch-server?vip=10",
{
// 请求方法
method: "POST",
// 请求头
headers: {
name:"Hello"
},
// 请求体
body: "username=admin&password=admin"
}).then(response => {
return response.json();
}).then(response => {
console.log(response)
});
}
axios
最热门的前端AJAX请求方法
Vue和React的推荐方法
const btns = document.querySelectorAll('button');
//配置 baseURL
axios.defaults.baseURL = "http://127.0.0.1:8000"
btns[0].onclick = function() {
//GET 请求
axios.get("/axios-server", {
//url 参数
params:{
id:100,
vip:7
},
//请求头信息
headers:{
name:"atguigu",
age:20
}
}).then(value => {
console.log(value);
})
}
btns[1].onclick = function() {
axios.post("/axios-server",
{
username: "admin",
password: "admin"
},
{
//url
params:{
id:200,
vip:9
},
//请求头参数d
headers:{
height:180,
weight:180,
}
})
}
btns[2].onclick = function() {
axios({
//请求方法
method: "POST",
//url
url: "/axios-server",
//url参数
params:{
vip:10,
level:30
},
//头信息
headers:{
a:100,
b:200
},
//请求体参数
data:{
username:"admin",
password:"admin"
}
}).then(response => {
console.log(response);
//响应状态码
console.log(response.status);
//响应状态字符串
console.log(response.statusText);
//响应头信息
console.log(response.headers);
//响应体
console.log(response.data);
})
}
参考资料&代码:
www.runoob.com/ajax/ajax-t…
www.w3school.com.cn/js/js_ajax_…
www.bilibili.com/video/BV1WC…