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

jQuery学习之AJAX

2015-08-09 16:45 711 查看

温习ajax

无需重新加载页面而向服务器发起异步请求的能力。

1.创建一个XHR实例

使用对象检测

var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else if(window.ActiveXObject){
xhr = new ActiveXObject('Msxml2.XMLHttp');
}else{
throw new Error('Ajax is not supported by this browser');
}


XHR方法和属性

方法

1.abort()

2.getAllResponseHeaders()

3.getResponseHeaders(name)

4.open(method,url,async,username,password)

5.send(content)

6.setRequestHeader(name,value)

属性

1.onreadystatechange

2.readyState

3.responseText

4.responseXML

5.status

6.statusText

2.发起请求

xhr.open('GET','/some/resource/url');

默认async为false,即为异步请求

xhr.send(null);

如果为post请求,需要xhr.send('a=1&b=2');

send方法的字符串必须符合正确的格式,URI编码,使用该函数即可encodeURLComponent

3.跟踪进展&获取响应

xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status >= 200 && xhr.status < 300){
document.getElementById('someContainer')
.innerHtml = xhr.reponseText;
}else{
//error
}
}
}


加载内容到元素上

使用原生的xhr则需要上面结合一起的例子

利用jQuery只需要一句话 $('#someContainer').load('/serverResource');

1.利用jQuery加载内容

load(url,parameters,callback)返回包装集

有时候需要筛选响应元素$('#someContainer').load('/serverResource #div');即可

serialize() 返回已格式化的查询字符串

serializeArray() 返回表单数据的数组

发起GET和POST请求

1.利用jQuery获取数据

$.get(url,parameters,callback)

$.get(url,{a:1,b:2},function(data){

alert(data);

})

2.获取JSON数据

$.getJSON(url,parameters,callback)

可以自动解析返回的JSON字符串,使得结果数据项可以在回调函数里面使用。

(function($) {
$.fn.emptySelect = function() {
return this.each(function(){
if (this.tagName=='SELECT') this.options.length = 0;
});
}

$.fn.loadSelect = function(optionsDataArray) {
return this.emptySelect().each(function(){
if (this.tagName=='SELECT') {
var selectElement = this;
$.each(optionsDataArray,function(index,optionData){
var option = new Option(optionData.caption,
optionData.value);
if ($.browser.msie) {
selectElement.add(option);
}
else {
selectElement.add(option,null);
}
});
}
});
}
})(jQuery);


3.发起POST请求

$.post(url,parameters,callback)

完全控制ajax请求

1.带着所有的修整发起ajax请求

$.ajax(options)

url string,type string get or post,data object post parameters,dataType string 响应类型 xml/hmtl/json/jsonp/script/text,timeout 数值,global 布尔,确实是否启用全局函数,contentType string 在请求上指定内容类型,如果省略 application/x-www-form-urlencoded,success,error,complete,beforeSend,async,processData
布尔类型 false的话,阻止已传递数据被加工为URL编码格式,默认情况下,数据被加工为URL编码格式(适用于application/x-www-form-urlencoded的请求),ifModified 布尔类型 true,只有相应内容没有被改变(Last-Modified标头)才允许请求成功。

2.设置请求的默认值

$.ajaxSetup()参数和ajax函数一致,但是ajaxSetup无法影响load

3.全局函数

ajaxStart(callback)

ajaxSend(callback)

ajaxSuccess(callback)

ajaxError(callback)

ajaxComplete(callback)

ajaxStop(callback)

把传入的回调函数附加到所有匹配元素上,一旦到达ajax请求处理的指定时刻就会触发回调函数

其中callback的参数包括type和target,type为全局函数类型的字符串,target为DOM元素

$(function(){
$('#goodButton').click(function(){
$.get('reflectData.php');
});
$('#badButton').click(function(){
$.get('returnError.php');
});
$('#successDisplay').ajaxSuccess(function(info){
$(info.target)
.append('<div>Success at '+new Date()+'</div>');
});
$('#errorDisplay').ajaxError(function(info,xhr){
$(info.target)
.append('<div>Failed at '+new Date()+'</div>')
.append('<div>Status: ' + xhr.status + ' ' +
xhr.statusText+'</div>');
});
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: