jquery.ajaxprefilter()函数用于指定预先处理ajax参数选项的回调函数。
在所有参数选项被jquery.ajax()函数处理之前,你可以使用该函数设置的回调函数来预先更改任何参数选项。
你还可以指定数据类型(datatype),从而只预先处理指定数据类型的参数选项。
该函数可以调用多次,以便于为不同数据类型的ajax请求指定不同的回调函数。
该函数属于全局jquery对象。
语法
jquery 1.5 新增该静态函数。
jquery.ajaxprefilter( [ datatype ,] handler )
参数
datatype可选/string类型
一个或多个用空格隔开的数据类型所组成的字符串。如果未指定该参数,则表示所有数据类型。可用的数据类型为xml、 html、 text、 json、 jsonp、 script。该字符串为它们之间的任意组合(多种类型用空格隔开),例如:xml、 text html、 script json jsonp。
handlerfunction类型
用于预处理参数选项的回调函数。它有以下3个参数:
options:(object对象)当前ajax请求的所有参数选项。
originaloptions:(object对象)传递给$.ajax()方法的未经修改的参数选项。
jqxhr:当前请求的jqxhr对象(经过jquery封装的xmlhttprequest对象)。
返回值
jquery.ajaxprefilter()函数没有返回值,或者说其返回值为undefined。
示例&说明
以下是与jquery.ajaxprefilter()函数相关的jquery示例代码,以演示jquery.ajaxprefilter()函数的具体用法:
//设置ajax的全局默认选项
$.ajaxsetup( {
url: "/index.html" , // 默认url
aysnc: false , // 默认同步加载
type: "post" , // 默认使用post方式
headers: { // 默认添加请求头
"author": "codeplayer" ,
"powered-by": "codeplayer"
} ,
error: function(jqxhr, textstatus, errormsg){ // 出错时默认的处理函数
// 提示形如:发送ajax请求到"/index.html"时出错[404]:not found
alert( '发送ajax请求到"' + this.url + '"时出错[' + jqxhr.status + ']:' + errormsg );
}
} );
// 指定预处理参数选项的函数
$.ajaxprefilter( function(options, originaloptions, jqxhr){
// options对象 包括accepts、crossdomain、contenttype、url、async、type、headers、error、datatype等许多参数选项
// originaloptions对象 就是你为$.ajax()方法传递的参数对象,也就是 { url: "/index.php" }
// jqxhr对象 就是经过jquery封装的xmlhttprequest对象(保留了其本身的属性和方法)
options.type = "get"; // 将请求方式改为get
options.headers = { }; // 清空自定义的请求头
});
// 执行ajax请求
$.ajax( {
url: "/index.php"
} );
jquery.ajaxprefilter()函数还可以只预处理指定数据类型(datatype)的ajax请求的参数选项。jquery代码如下所示:
//设置ajax的全局默认选项
$.ajaxsetup( {
url: "/index.html" , // 默认url
aysnc: false , // 默认同步加载
type: "post" , // 默认使用post方式
headers: { // 默认添加请求头
"author": "codeplayer" ,
"powered-by": "codeplayer"
} ,
error: function(jqxhr, textstatus, errormsg){ // 出错时默认的处理函数
// 提示形如:发送ajax请求到"/index.html"时出错[404]:not found
alert( '发送ajax请求到"' + this.url + '"时出错[' + jqxhr.status + ']:' + errormsg );
}
} );
// 指定预处理参数选项的函数,只预处理datatype为json或html类型的ajax请求
$.ajaxprefilter( "json html", function(options, originaloptions, jqxhr){
// options对象 包括accepts、crossdomain、contenttype、url、async、type、headers、error、datatype等许多参数选项
// originaloptions对象 就是你为$.ajax()方法传递的参数对象,也就是 { url: "/index.php" }
// jqxhr对象 就是经过jquery封装的xmlhttprequest对象(保留了其本身的属性和方法)
if( options.data == null && options.type == "post"){
options.type = "get"; // 将请求方式改为get
options.headers = { }; // 清空自定义的请求头
}
});
// 执行ajax请求
$.ajax( {
url: "/index.php"
} );
// 执行ajax请求(该请求会被预处理)
$.ajax( {
url: "action.php?type=json",
datatype: "json"
} );
以上就是jquery.ajaxprefilter() 函数使用详解的详细内容。