Ajax全称为“Asynchronous JavaScript and XML” (异步JavaScript和XML),它可以使浏览器不刷新而更新页面数据。Ajax的优势:
- 不需要插件支持。
- 优秀的用户体验。
- 提供Web程序的性能。
- 减轻服务器和宽带负担。
Ajax过程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| var request = new XMLHttpRequest(); // 新建XMLHttpRequest对象
request.onreadystatechange = function () { // 状态发生变化时,函数被回调
if (request.readyState === 4) { // 成功完成
// 判断响应结果:
if (request.status === 200) {
// 成功,通过responseText拿到响应的文本:
console.log(request.responseText);
} else {
// 失败,根据响应码判断失败原因:
console.log(request.status);
}
} else {
// HTTP请求还在继续...
}
}
request.open('GET', '/api/categories');
request.send();
|
对于低版本的IE,需要换一个ActiveXObject对象。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| var request = new ActiveXObject('Microsoft.XMLHTTP'); // 新建Microsoft.XMLHTTP对象
request.onreadystatechange = function () { // 状态发生变化时,函数被回调
if (request.readyState === 4) { // 成功完成
// 判断响应结果:
if (request.status === 200) {
// 成功,通过responseText拿到响应的文本:
console.log(request.responseText);
} else {
// 失败,根据响应码判断失败原因:
console.log(request.status);
}
} else {
// HTTP请求还在继续...
}
}
// 发送请求:
request.open('GET', '/api/categories');
request.send();
|
如果你想把标准写法和IE写法混在一起,可以这么写。
1
2
3
4
5
6
| var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
|
默认情况下,JavaScript在发送AJAX请求时,URL的域名必须和当前页面完全一致。
完全一致的意思是
- 域名要相同 : www.example.com和example.com不同
- 协议要相同 : http和https不同
- 端口号要相同 默认是:80端口,它和:8080就不同。
如果浏览器支持HTML5,那么就可以一劳永逸地使用新的跨域策略:CORS了。CORS全称Cross-Origin Resource Sharing,是HTML5规范定义的如何跨域访问资源。
jQuery中的Ajax
jQuery对AJax操作进行了封装,在jQuery中$.ajax()方法属于最底层的方法,第2层是load()、$.get()和$.post()方法,第3层是$.getScript()和$.getJSON()方法。
load()方法
load()方法是jQuery中最简单和最常使用的Ajax方法,能载入远程HTML代码并插入到DOM中。
1
| load(url [, data] [, callback])
|
参数名称 | 类型 | 说明 |
---|
url | String | 请求HTML页面的URL地址 |
data(可选) | Object | 发送至服务器的key/value数据 |
callback(可选) | Function | 请求完成时的回调函数,无论请求成功或失败 |
1
2
3
4
5
| $(function(){
$("#send").click(function(){
$("#resText").load("test.html");
})
})
|
load()方法如果有参数,则请求为post方式,否则为get方式
1
2
3
4
5
| //无参数,GET方式
$("#resText").load("test.html");
//有参数,POST方式
$("#resText").load("test.php", {name:"rain", age:"22"}, function(){//...});
|
load()方法的回调函数有3个参数,分别代表请求返回的内容、请求状态和XMLHttpRequest对象。
1
2
3
| $("#resText").load("test.html", function(responseText, textStatus, XMLHttpRequest){
});
|
$.get()和$.post()
1
| $.get(url [, data] [, callback] [, type]);
|
参数名称 | 类型 | 说明 |
---|
url | String | 请求的HTML页的URL地址。 |
data(可选) | Object | 发送至服务器的key/value数据作为QueryString附加到URL中。 |
callback(可选) | Function | 载入成功时的回调函数。 |
type(可选) | String | 返回内容格式,包括xml,html,script,json,text和_default |
$.post()和$.get()的结构和参数相同,只是提交方式的不同。
$.getScript()和$.getJSON()
有时候在页面初次加载的时候,取得全部的JavaScript是没有必要的。所以jQuery提供了$.getScript()方法来直接加载js文件。
1
2
3
4
5
| $(function(){
$("#send").click(function(){
$.getScript('test.js');
})
})
|
$.getJSON()方法的用法和$.getScript()相同,用于加载json文件。
1
2
3
4
5
| $(function(){
$("#send").click(function(){
$.getJSON("test.json");
})
})
|
$.ajax()方法
$.ajax()方法是jQuery最底层的Ajax实现。
例如:
1
2
3
4
5
6
7
8
9
| $(function(){
$('send').click(function(){
$.ajax({
type:"GET",
url:"test.js",
dataType:"script"
})
})
})
|
serialize()方法
有时候我们的表单很复杂,我们可以使用serialize()方法对一个jQuery对象序列化为字符串。
1
2
3
4
5
| $('send').click(function(){
$.get('get1.php', $('#form1').serialize(), function(data, textStatus){
$("#resText").html(data);
})
})
|
和serialize()方法类似的还有serializeArray()方法。
此外,我们还可以使用serialize()底层的核心方法$.param()方法来对一个数组或对象进行key/value进行序列化。
1
2
3
| var obj = {a:1, b:2, c:3}
var k = $.param(obj);
alert(k); //输出a=1&b=2&c=3
|
全局事件
比如在Ajax加载的时候,我们显示一个加载动画。
1
2
3
4
5
6
| $("#loading").ajaxStart(function(){
$(this).show();
})
$("#loading").ajaxStop(function(){
$(this).hide();
})
|