JQuery中的ajax技术详解
什么是ajax
AJAX(Asynchronous Javascript And XML)异步的Javascript和XML(准确的说跟xml已经关系不大,目前的互联网开发数据交互更多倾向于json),是一种异步的刷新技术,AJAX技术不算新颖的技术,基于javascript的一项能够跟服务端交互的对象(XMLHttpRequest)实现;
ajax的使用步骤
- 获取XMLHttpRequest对象
- 打开一个到服务端连接
- 发送请求
- 当请求状态改变时,接收来自服务端的响应数据
代码演示:
let url = "";
//1. 获取XMLHttpRequest对象
let xhr = new XMLHttpRequest();
//4. 当请求状态改变时,接收来自服务端的响应数据
xhr.onreadystatechange = function(){
if(this.readyState === 4 && this.status === 200){
console.log(xhr.responseText);
}
}
2. 打开一个到服务端连接
xhr.open('get/post', url);
//如果是post就设置请求头
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
3. 发送请求
xhr.send(data|null);
上面的是原生js中的jquery技术,那么我们现在来看看jquery对ajax的封装
JQuery中的ajax
$.ajax()
$.ajax({
type: 'post', //请求方式,一般为get, 或者post,默认get
url : url, //服务端地址
async: true, //是否发起异步请求, 默认true
cache: false, //是否缓存数据
dataType: 'json', //预期的服务端响应回来的数据类型 xml/json/html/text
contentType : "application/x-www-form-urlencoded",//数据的组织结构,将json的数据转换成地址拼接的方式
data : { //发送到后台的数目,一般是post会用到
method: "modifyPwd",
sno: 1,
oldpwd: '123',
newpwd: '123456'
},
beforeSend : function(){
//请求发送之后的回调
console.log('准备发送')
},
complete : function () {
//请求完成之后的回调
console.log('请求完成')
},
success: function(data){
//成功之后获取服务端的回调
console.log('获得响应:' , data)
},
error: function(error){
//失败之后的回调
console.log('失败信息:' + error);
}
});
$.get() & $.post()
$.get(url, function(data){
console.log(data);
});
$.post(url, data, function(data){
console.log(data);
})
$.getJSON()
可以获取json对象的响应数据, 也可以读取.json的文件
$.getJSON(url,function(data){
console.log(data);
})
总结
jquery中对于ajax的封装还是可以大大提高我们的开发效率, 同时也提供了更丰富的请求格式, 提供了更简便的操作