1.原生JavaScript封装Ajax
var Ajax = {
get: function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status == 304) {
console.log(xhr.responseText)
callback(xhr.responseText);
}
}
}
xhr.send();
},
post: function(url, data, callback) {
var xhr = new XMLHttpRequest()
xhr.open('POST', url, false)
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status == 304) {
console.log(xhr.responseText)
callback(xhr.response)
}
}
}
xhr.send(data)
}
}
2.使用JQuery实现Ajax
$.ajax({
//请求方式
type: "POST",
//请求的媒体类型
contentType: "application/json;charset=UTF-8",
//请求地址
url: "/login",
//数据,json字符串
data: JSON.stringify({
"username": username,
"password": password
}),
//请求成功
success: function(data) {
console.log("发送请求成功,处理返回数据")
}
},
//请求失败,包含具体的错误信息
})