JQ中的Ajax的封装
1.认识JQ中ajax的封装
jQ 对于ajax的封装有两层实现;$.ajax 为底层封装实现;基于 $.ajax ,分别实现了$.get 与$.post 的高层封装实现;
2.Ajax的底层实现基本语法:
async: 布尔类型,代表是否异步,true代表异步,false同步,默认为true
cache: 是否缓存,布尔类型,true代表缓存,false代表不缓存,默认为true
complete: 当Ajax状态码(readyState)为4的时候所触发的回调函数
contentType: 发送信息至服务器时内容编码类型;(默认: "application/x-www-form-urlencoded")
data: 要求是一个字符串格式,Ajax发送时所传递的数据
dataType: 期待的返回值类型,可以是text,xml,json,默认为text类型
success: 当Ajax状态码为4且响应状态码为200时所触发的回调函数
type: Ajax发送网络请求的方式,(默认: "GET");
url: 请求的url地址
GET请求
<body>
<input type="button" value="点击" id="btu">
</body>
<script>
$('#btu').click(function(){
//get请求
$.ajax({
url:'/jq_ajax_get',
success:function(data){
alert(data);
}
});
});
</script>
POST请求:
<body>
<input type="button" value="点击" id="btu">
</body>
<script>
$('#btu').click(function () {
$.ajax({
url: '/jq_ajax_post',
type: 'post',
data: 'id=1111',
success: function (data) {
alert(data);
},
// async:false,
});
// alert(22); //检验同步异步
});
</script>
3.ajax的高层实现:
GET应用:
基本语法:$.get(url, [data], [callback], [type])
url:待载入页面的URL地址
data:待发送 Key/value 参数。
callback:载入成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default。
案例:
<body>
<input type="button" value="点击" id="btu">
</body>
<script>
$('#btu').click(function(){
$.get('/jq_ajax_get',function(data){
alert(data);
},'json');
});
</script>
POST应用:
$.post(url, [data], [callback], [type])
url:发送请求地址。
data:待发送 Key/value 参数。
callback:发送成功时回调函数。t
ype:返回内容格式,xml, html, script, json, text, _default。
案例:
<body>
<input type="button" value="点击" id="btu">
</body>
<script>
$('#btu').click(function () {
$.post('/jq_ajax_post',
{ id: '11' },
function (data) {
alert(data);
});
});
</script>

