您的位置:首页 > Web前端 > JQuery

jQuery Ajax【下】

2016-05-12 23:06 465 查看
学习要点:

1.加载请求

2.错误处理

3.请求全局事件

4.JSON 和 JSONP

5.jqXHR 对象

一、加载请求

当网速较慢的时候,我们的请求迟迟没有被响应

这时候,用户就会感到不耐烦,因此我们需要一些友好的提示

JQ提供了两个全局事件,startAjax和stopAjax分别在ajax发生和结束请求的时候触发

// dome.html
<div></div>

// ajax.php
<?php echo 111;?>

$.ajax({
type : "get",
url : "ajax.php",
success : function (response, status, xhr) {
alert(response);
}
});
$(document).ajaxStart(function () {
$("div").html("数据加载中");
});
$(document).ajaxStop(function () {
$("div").html("数据加载完毕");
});


如果请求超时,我们可以设置超时的时间

首先我们来模拟一下,在ajax.php将响应时间加长

<?php
sleep(3000);
echo 111;
?>

$.ajax({
timeout : 2000,
type : "get",
url : "ajax.php",
success : function (response, status, xhr) {
alert(response);
},
error : function (response, status, xhr) {
alert("加载出错或者超时");
}
});
$(document).ajaxStart(function () {
$("div").html("数据加载中");
});
$(document).ajaxStop(function () {
$("div").html("数据加载完毕");
});


如果ajax不想触发全局事件,我们可以设置

$.ajax({
global : false,     // 这样ajaxStart和ajaxStop事件将不会触发了
type : "get",
url : "ajax.php",
success : function (response, status, xhr) {
alert(response);
}
});
$(document).ajaxStart(function () {
$("div").html("数据加载中");
});
$(document).ajaxStop(function () {
$("div").html("数据加载完毕");
});


二、错误处理

由于种种原因的限制,例如数据不存在或者网速的问题,我们的请求可能出来种种的问题,

这时我们就需要对错误进行处理,并且把他们表现出来

$.ajax()使用属性提示错误

$.ajax({
timeout : 2000,
type : "get",
url : "ajax.php",
success : function (response, status, xhr) {
alert(response);
},
error : function (xhr, errorText, errorStatus) {
alert(xhr.status + " : " + xhr.errorText);      // 0 : undefined
}
});
$(document).ajaxStart(function () {
$("div").html("数据加载中");
});
$(document).ajaxStop(function () {
$("div").html("数据加载完毕");
});


$.post()方法使用连缀.error()方法

在这里,test.php本身是不存在的

$.post("test.php").error(function (xhr, status, info) {
alert(xhr.status + " : " + xhr.errorText);      // 404 : undefined
alert(status + " : " + info);                   // error : Not Found
});


同时我们可以用.ajaxError()全局事件来提示错误

$(document).ajaxError(function (event, xhr, settings, infoError) {
alert(xhr.status + " : " + xhr.errorText);      // 0 : undefined
alert(settings + " : " + infoError);            // [object Object] : timeout
});
$.ajax({
timeout : 2000,
type : "get",
url : "ajax.php",
success : function (response, status, xhr) {
alert(response);
}
});


三、请求全局事件

在前面我们介绍了ajaxStart()、ajaxStop()和ajaxError()这三个全局事件

其实还有全局事件我们没有介绍,这里我们来列举几个常用的

1.第一组.ajaxSuccess(),对应一个局部方法:.success(),请求成功完成时执行。

<?php echo 111; ?>

// 局部方法.success()
$.ajax({
type : "get",
url : "ajax.php"
}).success(function (response, status, xhr) {
alert(response);        // 111
});
// 全局事件
$(document).ajaxSuccess(function (event, xhr, settings) {
alert(xhr.responseText);        // 111
});
$.ajax({
type : "get",
url : "ajax.php"
});


PS : 全局事件方法是所有 Ajax 请求都会触发到,并且只能绑定在 document 上。而局部方法,则针对某个 Ajax。

2.第二组:.ajaxComplete(),对应一个局部方法:.complete(),请求完成后注册一个回调函数。

局部方法.complete()

$.ajax({
type : "get",
url : "ajax.php"
}).complete(function (response, status, xhr) {
alert("complete");      // complete
});


全局事件

$(document).ajaxComplete(function (event, xhr, settings) {
// 遍历setteings
for (var s in settings) {
console.log(s + " : " + settings[s]);   // isLocal : false  ...
};
});
$.ajax({
type : "get",
url : "ajax.php"
});


3.第三组.ajaxSend(),没有对应的局部方法,只有属性 beforeSend,请求发送之前要绑定的函数。

ajax属性

$.ajax({
type : "get",
url : "ajax.php",
beforeSend : function (xhr, settings) {
alert("在发送之前的属性");      // 在发送之前的属性
}
});


全局事件

$(document).ajaxSend(function (event, xhr, settings) {
alert("数据发送之前");        // 数据发送之前
});
$.ajax({
type : "get",
url : "ajax.php"
});


四、JSON与JSONP

如果在同一个域下,$.ajax()方法只要设置 dataType 属性即可加载 JSON 文件。

而在非同域下,可以使用 JSONP,但也是有条件的。

在同域下

// ajax.json
{"name" : "zhang", "age" : 23}

$.ajax({
type : "post",
url : "ajax.json",
dataType : "json",
success : function (response, status, xhr) {
for (var i in response) {
alert(i + " : " + response[i]); // name : zhang ...
}
}
});


如果想跨域操作文件的话,我们就必须使用 JSONP

跨域的 PHP 端文件

http://114.215.112.235/test.php

<?php
$arr = array('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
$result = json_encode($arr);
$callback = $_GET['callback'];
echo $callback."($result)";
?>


$.getJSON()方法跨越获取JSON文件

$.getJSON("http://114.215.112.235/test.php?callback=?", function (response) {
console.log(response);
});


$.ajax()跨域获取JSON

$.ajax({
url : 'http://114.215.112.235/test.php?callback=?',
dataType : "jsonp",
success : function (response, status, xhr) {
console(response);
alert(response.a);
}
});


五.jqXHR 对象

在之前我们使用的局部方法: .success()、.error()和.complete()方法,

使用的对象并非是XMLHttpRequest对象,而是jqXHR对象,

且我们推荐使用.done()、.fail()和.always()方法

var jqXHR = $.ajax({
url : "ajax.php",
type : "get"
});
for (var i in jqXHR) {
console.log(i + " : " + jqXHR[i]);      // readyState : 1  ....
}
jqXHR.done(function (response) {
alert(response);            // lll
});


使用 jqXHR 的连缀方式比$.ajax()的属性方式有三大好处:

1.可连缀操作,可读性大大提高;

2.可以多次执行同一个回调函数;

3.为多个操作指定回调函数;

多个操作指定回调函数

// test1.php 和 test2.php
<?php echo "I am test1.php";?>
<?php echo "I am test2.php";?>

var jqXHR = $.ajax("test1.php");
var jqXHR2 = $.ajax("test2.php");
$.when(jqXHR, jqXHR2).done(function (r1, r2) {
// 遍历两个jqXHR对象
for(var v1 in r1) {
console.log(v1 + " : " + r1[v1]);       //0 : I am test1.php        ....
}
for(var v2 in r2) {
console.log(v2 + " : " + r2[v2]);       //0 : I am test2.php        ....
}
})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: