ajax详解以及各种封装
warning:
这篇文章距离上次修改已过206天,其中的内容可能已经有所变动。
AJAX(Asynchronous JavaScript and XML)技术能够让浏览器与服务器通信而无需刷新页面。以下是AJAX的详解以及不同的封装方式。
- 原生JavaScript的AJAX请求
var xhr = new XMLHttpRequest();
xhr.open("POST", "/server", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
}
xhr.send("user=zhangsan&age=20");
- jQuery的AJAX请求
$.ajax({
url: "/server",
type: "POST",
data: {user: "zhangsan", age: "20"},
success: function (response) {
console.log(response);
}
});
- 使用jQuery的
get
和post
方法封装AJAX请求
$.post("/server", {user: "zhangsan", age: "20"}, function (response) {
console.log(response);
});
$.get("/server", {user: "zhangsan", age: "20"}, function (response) {
console.log(response);
});
- 使用fetch API发送请求
fetch('/server', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({user: "zhangsan", age: "20"})
}).then(response => response.json()).then(data => console.log(data));
- 使用axios库发送请求
axios.post('/server', {user: "zhangsan", age: "20"})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
以上都是AJAX请求的封装方式,开发者可以根据自己的需求选择合适的方式。其中,fetch
和axios
是现代的JavaScript技术,它们提供了更加强大和灵活的功能。
评论已关闭