jQuery中的Ajax
文章目录
jQuery不仅对JavaScript语言进行了封装,也对Ajax异步交互进行了封装。jQuery提供了六个Ajax操作的方法:
- load()方法
- $get()方法和 $.post()方法
- $ajax()方法
- $getScript(方法和 $getJSON()方法
jQuery除了封装了六个Ajax操作的方法,还提供了以下几种事件:
-
ajaxStart()和ajaxStop()事件
-
ajaxComplete()事件、ajaxSend()事件、ajaxError()事件和ajaxSuccess()事件
load()方法
load()方法是jQuery中最为简单的Ajax方法,其语法结构如下:
$element.load(url,[data],[callback]);
-
url: 请求HTML页面的url地址。
-
data: 发送给服务器端的key/value形式的数据内容。
-
callback: Ajax请求完成时的回调函数。
$('button').click(function() {
$('div').load('server.js');
});
注意: load()方法的请求方式由是否传递参数决定。即不传递 data 参数,为GET方式;传递 data 参数,为POST方式。
代码演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>load()方法</title>
</head>
<body>
<button>按钮</button>
<script src="js/jquery-1.12.4.js"></script>
<script>
$("button").click(function () {
/*
load(url, [data], [callback])方法
* 参数
* url - 异步请求的地址
* data - 异步请求的数据
* callback - 异步请求成功后的回调函数
* 返回值 - 服务器端的响应结果
* 注意 - 自动将返回结果写入到目标元素中
*/
$("button").load("data/server2.json", function () {
console.log("异步请求成功...");
});
});
</script>
</body>
</html>
如果不传入data参数,默认为GET请求方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>load()方法</title>
</head>
<body>
<button>按钮</button>
<script src="js/jquery-1.12.4.js"></script>
<script>
$("button").click(function () {
/*
load(url, [data], [callback])方法
* 参数
* url - 异步请求的地址
* data - 异步请求的数据
* 如果省略请求数据的话,当前的请求数据的话,当前的请求方式为GET
* 如果发送请求数据的话,当前的请求方式为POST
* callback - 异步请求成功后的回调函数
* 返回值 - 服务器端的响应结果
* 注意 - 自动将返回结果写入到目标元素中
*/
$("button").load("data/server2.json", { name: "张无忌" }, function () {
console.log("异步请求成功...");
});
});
</script>
</body>
</html>
如果传入data参数,默认为POST请求方式
$.get()与 $.post()方法
-
$get(方法使用GET方式向服务器端发送异步请求。其语法结构如下:
$.get(url,[data],[callback],[type]);
-
url: 请求HTML页面的url地址。
-
data: 发送给服务器端的key/value形式的数据内容。
-
callback: Ajax请求完成时的回调函数。
-
type: 设置返回数据内容的格式。值为xml、html、script、json、text和_default。
$('button').click(function(){
$.get('server.js',function(data, textStatus){
//data:表示服务器端响应的数据内容
//textStatus: success、error、notmodified和timeout四种请求状态之一
});
});
代码演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>get()与post()方法</title>
</head>
<body>
<button>按钮</button>
<script src="js/jquery-1.12.4.js"></script>
<script>
$("button").click(function () {
/*
get(url, [data], [callback], [type])方法 - 请求方式为GET
* 参数
* url - 异步请求地址
* data - 异步请求的数据
* callback - 异步请求成功后的回调函数
*/
$.get("data/server2.json", function () {
console.log("异步请求成功啦...");
});
});
</script>
</body>
</html>
效果如下
可以看到,如果不传递 data 参数的话,默认为GET请求,并且请求URL是不带参数的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>get()与post()方法</title>
</head>
<body>
<button>按钮</button>
<script src="js/jquery-1.12.4.js"></script>
<script>
$("button").click(function () {
/*
get(url, [data], [callback], [type])方法 - 请求方式为GET
* 参数
* url - 异步请求地址
* data - 异步请求的数据
* callback - 异步请求成功后的回调函数
*/
$.get("data/server2.json", { name: "张无忌" }, function () {
console.log("异步请求成功啦...");
});
});
</script>
</body>
</html>
可以看到,如果传递 data 参数的话,默认也为GET请求,并且请求URL是带参数的
callback中响应结果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>get()与post()方法</title>
</head>
<body>
<button>按钮</button>
<script src="js/jquery-1.12.4.js"></script>
<script>
$("button").click(function () {
/*
get(url, [data], [callback], [type])方法 - 请求方式为GET
* 参数
* url - 异步请求地址
* data - 异步请求的数据
* callback - 异步请求成功后的回调函数
function(response){}
* type - 设置服务器端响应结果的格式
xml、html、script、json、text等
*/
$.get("data/server2.json", { name: "张无忌" }, function (response) {
console.log(response);
});
});
</script>
</body>
</html>
不传递type类型默认返回json格式的数据内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>get()与post()方法</title>
</head>
<body>
<button>按钮</button>
<script src="js/jquery-1.12.4.js"></script>
<script>
$("button").click(function () {
/*
get(url, [data], [callback], [type])方法 - 请求方式为GET
* 参数
* url - 异步请求地址
* data - 异步请求的数据
* callback - 异步请求成功后的回调函数
function(response){}
* type - 设置服务器端响应结果的格式
xml、html、script、json、text等
*/
$.get(
"data/server2.json",
{ name: "张无忌" },
function (response) {
console.log(response);
},
"text"
);
});
</script>
</body>
</html>
不传递type类型会返回指定格式的数据内容
$.post方法同样用法
$.ajax()方法
具体可以参考 jQuery文档 jQuery.ajax(url,[settings])
$ajax()方法是jQuery中最为底层的Ajax方法,其语法结构如下:
$.ajax(url,[settings]);
-
url: 请求HTML页面的url地址。
-
settings: key/value形式的请求设置,所有参数都是可选的。
$("button").click(function(){
$.ajax({
url:"server.js",
type:"post",
data:"this is ajax",
success:function(data){
console.log(data);//服务器响应回数据之后的处理逻辑
}
});
);
代码演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ajax()方法</title>
</head>
<body>
<button>按钮</button>
<script src="js/jquery-1.12.4.js"></script>
<script>
$("button").click(function () {
/*
$.ajax(url, [settings])方法
* 参数
* url - 请求地址
* settings - 设置异步请求的参数
* settings选项 - 对象类型
* type - 设置请求方式
* data - 发送给服务器端的请求数据
* dataType - 服务器端响应结果的格式
* success - 异步请求成功后的回调函数
function(data, textStatus, jqXHR){}
* data - 表示服务器端响应的结果
* textStatus - 表示服务器端当前的状态
* jqXHR - Ajax中的核心对象
*/
$.ajax("data/server2.json", {
type: "get",
dataType: "text",
success: function (data) {
console.log(data);
},
});
});
</script>
</body>
</html>
$.getScript()方法
$getScript(方法是jQuery中用于动态加载指定JavaScript文件,其语法结构如下:
$.getScript(url,[callback);
- url: 请求JavaScript文件的url地址。
- callback: 指定JavaScript文件成功加载后的回调函数。
$('button').click(function(){
$.getScript('test.js');
});
代码演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>getScript()方法</title>
</head>
<body>
<button>按钮</button>
<script src="js/jquery-1.12.4.js"></script>
<script>
$("button").click(function () {
// 动态加载指定JavaScript文件,并且执行
$.getScript("data/server3.js", function (data) {
console.log(data);
eval(data);
});
});
</script>
</body>
</html>
$.getJSON()方法
$getuJSON(方法是jQuery中用于动态加载指定JSON格式的数据内容,其语法结构如下:
$.getJSON(url,[data],[callback]);
-
url: 请求JavaScript文件的url地址。
-
data: 发送给服务器端的key/value形式的数据内容。
-
callback: 指定JavaScript文件成功加载后的回调函数。
$('button').click(function(){
$.getJSON('test.json', function(data){
console.log(data);
};
};
代码演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>gtJSON()方法</title>
</head>
<body>
<button>按钮</button>
<script src="js/jquery-1.12.4.js"></script>
<script>
$("button").click(function () {
// getJSON()方法的请求方式为GET
$.getJSON("data/server2.json", { name: "张无忌" }, function (data) {
console.log(data);
});
});
</script>
</body>
</html>
Ajax的全局事件
加载请求: .ajaxStart() 和 .ajaxstop()
$(document).ajaxStart(function(){
$('.loading').show();
}).ajaxStop(function(){
$('.loading').hide();
});
错误处理: .ajaxError()
//1 $.ajax()使用属性提示错误
$('form input[type=button]').click(function(){
$.ajax({
type:"post",
url:"test1.php",
async:true,
data:$('form').serialize(),
success:function(response,status,xhr){
$('#box').html(response);
},
// timeout:3000
// global:false
error:function(xhr,errorText,errorType){
// alert(errorText + ':' +errorType);
alert(xhr.status + ':' +xhr.statusText);
}
});
});
//2 $.post()使用连缀.error()方法提示错误,将被.fail()取代
$('form input[type=button]').click(function(){
$.post('test1.php').error(function(xhr,errorText,errorType){
alert(errorText + ':' +errorType);
alert(xhr.status + ':' +xhr.statusText);
});
});
//3 使用全局.ajaxError()方法
$(document).ajaxError(function(event,xhr,settings,info){
alert(event.type);
alert(event.target);
for(var i in event){ //打印出event的所有属性
document.write(i + '<br />');
}
});
.ajaxSuccess(),对应一个局部方法:.success(),请求成功完成时执行。
.ajaxComplete(),对应一个局部方法:.complete(),请求完成后注册一个回调函数。
.ajaxSend(),没有对应的局部方法,只有属性 beforeSend,请求发送之前要绑定的函数。
//$.post()使用全局
$('form input[type=button]').click(function(){
$.post('test.php',$('form').serialize());
});
$('document').ajaxSend(function(){
alert(发送请求之前执行);
}).ajaxComplete(function(response,status,xhr){
alert('请求完成后,不管是否失败成功');
}).ajaxSuccess(function(event,xhr,settrings){
alert('请求成功后,不管是否成功');
}).ajaxError(function(event,xhr,settrings){
alert('请求失败后');
});
//$.post()使用局部
$('form input[type=button]').click(function(){
$.post('test.php',$('form').serialize()).success(function(){
alert('请求成功后');
}).complete(function(){
alert('请求完成后');
}).error(function(){
alert('请求失败后');
});
});
//$.ajax()使用属性
$('form input[type=button]').click(function(){
$.ajax({
type:"post",
url:"test1.php",
async:true,
data:$('form').serialize(),
success:function(response,status,xhr){
alert('请求成功后');
},
complete:function(){
alert('请求完成后,不管失败成功');
},
beforeSend:function(){
alert('发送请求之前');
},
error:function(xhr,errorText,errorType){
alert('请求失败后');
}
});
});
注:在 jQuery1.5 版本以后,使用**.success()、.error()和.complete()连缀的方法,可以用.done()、.fail()和.always()**取代。