日常工作中(主要使用ASP.net),我需要編寫很多JavaScript代碼。我做的最重復(fù)的任務(wù)之一是jQuery Ajax調(diào)用。你看:
$.ajax({
type: "POST",
url: "MyPage.aspx/MyWebMethod",
data: "{parameter:value,parameter:value}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//function called successfull
},
error: function(msg) {
//some error happened
}
});
我不知道對(duì)您來說是否相同,但是對(duì)我來說用這種語法編寫調(diào)用太麻煩了。而且,以前必須按照已知規(guī)則使用參數(shù)構(gòu)建字符串以傳遞給WebMethod:字符串必須用引號(hào)傳遞,數(shù)字不能傳遞,等等。
因此,我決定創(chuàng)建一個(gè)小而有用的JavaScript類來幫助我有了這個(gè)特定的問題,現(xiàn)在我已經(jīng)完成了jQuery Ajax調(diào)用,這對(duì)我來說非常友好。
在類構(gòu)造函數(shù)中,我傳遞頁面名稱,方法名稱以及成功和錯(cuò)誤函數(shù)。以后,我會(huì)根據(jù)需要對(duì)addParam方法進(jìn)行盡可能多的調(diào)用。最后,我調(diào)用run方法進(jìn)行Ajax調(diào)用。成功函數(shù)和錯(cuò)誤函數(shù)必須分別編寫。
參數(shù)根據(jù)其類型進(jìn)行處理。如果參數(shù)是字符串,則使用引號(hào)。如果是數(shù)字,我不會(huì)。日期參數(shù)是一種特殊情況。在這種情況下,我使用JavaScript日期對(duì)象的getTime()函數(shù),該函數(shù)給了我自1970年1月1日以來的日期的毫秒數(shù)。后來,我將該值轉(zhuǎn)換為UTC時(shí)間,這樣我得到了一個(gè)最終的毫秒數(shù),即我可以將Int64值傳遞給我的VB.net(或C#)代碼,用它來重建.Net中的日期值。
這是我的jAjax類的完整列表(末尾帶有日期幫助器功能):
function jAjax(pageName, methodName, successFunc, errorFunc) {
//stores the page name
this.pageName=pageName;
//stores the method name
this.methodName=methodName;
//stores the success function
this.successFunc=successFunc;
//stores the error function
this.errorFunc=errorFunc;
//initializes the parameter names array
this.paramNames=new Array();
//initializes the parameter values array
this.paramValues=new Array();
//method for add a new parameter (simply pushes to the names and values arrays)
this.addParam=function(name, value) {
this.paramNames.push(name);
this.paramValues.push(value);
}
//method to run the jQuery ajax request
this.run=function() {
//initializes the parameter data string
var dataStr='{';
//iterate thru the parameters arrays to compose the parameter data string
for (var k=0; k < this.paramNames.length; k++) {
//append the parameter name
dataStr +=this.paramNames[k] + ':';
if (typeof this.paramValues[k]=='string') {
//string parameter, append between quotes
dataStr +='"' + this.paramValues[k] + '",';
} else if (typeof this.paramValues[k]=='number') {
//number parameter, append "as-is" calling toString()
dataStr +=this.paramValues[k].toString() + ',';
} else if (typeof this.paramValues[k]=='object') {
if (this.paramValues[k].getTime !=undefined) {
//date value
//call to my getUtcTime function to get the number of
//milliseconds (since january 1, 1970) in UTC format
//and append as a number
dataStr +=getUtcTime(this.paramValues[k]).toString() + ',';
} else {
//object value
//because I don't know what's this, append the toString()
//output
dataStr +='"' + this.paramValues[k].toString() + '",';
}
}
}
//if some parameter added, remove the trailing ","
if (dataStr.length > 1) dataStr=dataStr.substr(0, dataStr.length - 1);
//close the parameter data string
dataStr +='}';
//do the jQuery ajax call, using the parameter data string
//and the success and error functions
$.ajax({
type: "POST",
url: this.pageName + "/" + this.methodName,
data: dataStr,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
successFunc(msg);
},
error: function(msg) {
errorFunc(msg);
}
});
}
}
function getUtcTime(dateValue) {
//get the number of milliseconds since january 1, 1970
var time=dateValue.getTime();
//get the UTC time offset in minutes. if you created your date with
//new Date(), maybe this contains a value. but if you compose the date
//by yourself (i.e. var myDate=new Date(1984,5,21,12,53,11)) this will
//be zero
var minutes=dateValue.getTimezoneOffset() * -1;
//get the milliseconds value
var ms=minutes * 60000;
//add to the original milliseconds value so we get the GMT exact value
return time + ms;
}
這是使用的語法:
var ajaxCall=new jAjax('MyPage.aspx','MyWebMethod',successFunc,errorFunc);
ajaxCall.addParam('s','this is a string');
ajaxCall.addParam('n',34);
ajaxCall.addParam('d',new Date());
ajaxCall.run();
function successFunc(msg) {
...
}
function errorFunc(msg) {
}
另外一個(gè)好處是,您可以將成功和錯(cuò)誤功能重新用于幾個(gè)ajax調(diào)用。
希望對(duì)您有幫助!!隨時(shí)在您的應(yīng)用程序中使用jAjax類。
JAX 是一種與服務(wù)器交換數(shù)據(jù)的技術(shù),可以在補(bǔ)充在整個(gè)頁面的情況下更新網(wǎng)頁的一部分。接下來通過本文給大家介紹ajax一些常用方法,大家有需要可以一起學(xué)習(xí)。
1.url:
要求為String類型的參數(shù),(默認(rèn)為當(dāng)前頁地址)發(fā)送請(qǐng)求的地址。
2.type:
要求為String類型的參數(shù),請(qǐng)求方式(post或get)默認(rèn)為get。注意其他http請(qǐng)求方法,例如put和delete也可以使用,但僅部分瀏覽器支持。
3.timeout:
要求為Number類型的參數(shù),設(shè)置請(qǐng)求超時(shí)時(shí)間(毫秒)。此設(shè)置將覆蓋$.ajaxSetup()方法的全局設(shè)置。
4.async:
要求為Boolean類型的參數(shù),默認(rèn)設(shè)置為true,所有請(qǐng)求均為異步請(qǐng)求。如果需要發(fā)送同步請(qǐng)求,請(qǐng)將此選項(xiàng)設(shè)置為false。注意,同步請(qǐng)求將鎖住瀏覽器,用戶其他操作必須等待請(qǐng)求完成才可以執(zhí)行。
5.cache:
要求為Boolean類型的參數(shù),默認(rèn)為true(當(dāng)dataType為script時(shí),默認(rèn)為false),設(shè)置為false將不會(huì)從瀏覽器緩存中加載請(qǐng)求信息。
6.data:
要求為Object或String類型的參數(shù),發(fā)送到服務(wù)器的數(shù)據(jù)。如果已經(jīng)不是字符串,將自動(dòng)轉(zhuǎn)換為字符串格式。get請(qǐng)求中將附加在url后。防止這種自動(dòng)轉(zhuǎn)換,可以查看 processData選項(xiàng)。對(duì)象必須為key/value格式,例如{foo1:"bar1",foo2:"bar2"}轉(zhuǎn)換為&foo1=bar1&foo2=bar2。如果是數(shù)組,JQuery將自動(dòng)為不同值對(duì)應(yīng)同一個(gè)名稱。例如{foo:["bar1","bar2"]}轉(zhuǎn)換為&foo=bar1&foo=bar2。
7.dataType:
要求為String類型的參數(shù),預(yù)期服務(wù)器返回的數(shù)據(jù)類型。如果不指定,JQuery將自動(dòng)根據(jù)http包mime信息返回responseXML或responseText,并作為回調(diào)函數(shù)參數(shù)傳遞。可用的類型如下:
xml:返回XML文檔,可用JQuery處理。
html:返回純文本HTML信息;包含的script標(biāo)簽會(huì)在插入DOM時(shí)執(zhí)行。
script:返回純文本JavaScript代碼。不會(huì)自動(dòng)緩存結(jié)果。除非設(shè)置了cache參數(shù)。注意在遠(yuǎn)程請(qǐng)求時(shí)(不在同一個(gè)域下),所有post請(qǐng)求都將轉(zhuǎn)為get請(qǐng)求。
json:返回JSON數(shù)據(jù)。
jsonp:JSONP格式。使用SONP形式調(diào)用函數(shù)時(shí),例如myurl?callback=?,JQuery將自動(dòng)替換后一個(gè)“?”為正確的函數(shù)名,以執(zhí)行回調(diào)函數(shù)。
text:返回純文本字符串。
8.beforeSend:
要求為Function類型的參數(shù),發(fā)送請(qǐng)求前可以修改XMLHttpRequest對(duì)象的函數(shù),例如添加自定義HTTP頭。在beforeSend中如果返回false可以取消本次ajax請(qǐng)求。XMLHttpRequest對(duì)象是惟一的參數(shù)。
function(XMLHttpRequest){
this; //調(diào)用本次ajax請(qǐng)求時(shí)傳遞的options參數(shù)
}
9.complete:
要求為Function類型的參數(shù),請(qǐng)求完成后調(diào)用的回調(diào)函數(shù)(請(qǐng)求成功或失敗時(shí)均調(diào)用)。參數(shù):XMLHttpRequest對(duì)象和一個(gè)描述成功請(qǐng)求類型的字符串。
function(XMLHttpRequest, textStatus){
this; //調(diào)用本次ajax請(qǐng)求時(shí)傳遞的options參數(shù)
}
10.success:
要求為Function類型的參數(shù),請(qǐng)求成功后調(diào)用的回調(diào)函數(shù),有兩個(gè)參數(shù)。
(1)由服務(wù)器返回,并根據(jù)dataType參數(shù)進(jìn)行處理后的數(shù)據(jù)。
(2)描述狀態(tài)的字符串。
function(data, textStatus){
//data可能是xmlDoc、jsonObj、html、text等等
this; //調(diào)用本次ajax請(qǐng)求時(shí)傳遞的options參數(shù)
}
11.error:
要求為Function類型的參數(shù),請(qǐng)求失敗時(shí)被調(diào)用的函數(shù)。該函數(shù)有3個(gè)參數(shù),即XMLHttpRequest對(duì)象、錯(cuò)誤信息、捕獲的錯(cuò)誤對(duì)象(可選)。ajax事件函數(shù)如下:
function(XMLHttpRequest, textStatus, errorThrown){
//通常情況下textStatus和errorThrown只有其中一個(gè)包含信息
this; //調(diào)用本次ajax請(qǐng)求時(shí)傳遞的options參數(shù)
}
12.contentType:
要求為String類型的參數(shù),當(dāng)發(fā)送信息至服務(wù)器時(shí),內(nèi)容編碼類型默認(rèn)為"application/x-www-form-urlencoded"。該默認(rèn)值適合大多數(shù)應(yīng)用場(chǎng)合。
13.dataFilter:
要求為Function類型的參數(shù),給Ajax返回的原始數(shù)據(jù)進(jìn)行預(yù)處理的函數(shù)。提供data和type兩個(gè)參數(shù)。data是Ajax返回的原始數(shù)據(jù),type是調(diào)用jQuery.ajax時(shí)提供的dataType參數(shù)。函數(shù)返回的值將由jQuery進(jìn)一步處理。
function(data, type){
//返回處理后的數(shù)據(jù)
return data;
}
14.dataFilter:
要求為Function類型的參數(shù),給Ajax返回的原始數(shù)據(jù)進(jìn)行預(yù)處理的函數(shù)。提供data和type兩個(gè)參數(shù)。data是Ajax返回的原始數(shù)據(jù),type是調(diào)用jQuery.ajax時(shí)提供的dataType參數(shù)。函數(shù)返回的值將由jQuery進(jìn)一步處理。
function(data, type){
//返回處理后的數(shù)據(jù)
return data;
}
15.global:
要求為Boolean類型的參數(shù),默認(rèn)為true。表示是否觸發(fā)全局ajax事件。設(shè)置為false將不會(huì)觸發(fā)全局ajax事件,ajaxStart或ajaxStop可用于控制各種ajax事件。
16.ifModified:
要求為Boolean類型的參數(shù),默認(rèn)為false。僅在服務(wù)器數(shù)據(jù)改變時(shí)獲取新數(shù)據(jù)。服務(wù)器數(shù)據(jù)改變判斷的依據(jù)是Last-Modified頭信息。默認(rèn)值是false,即忽略頭信息。
17.jsonp:
要求為String類型的參數(shù),在一個(gè)jsonp請(qǐng)求中重寫回調(diào)函數(shù)的名字。該值用來替代在"callback=?"這種GET或POST請(qǐng)求中URL參數(shù)里的"callback"部分,例如{jsonp:'onJsonPLoad'}會(huì)導(dǎo)致將"onJsonPLoad=?"傳給服務(wù)器。
18.username:
要求為String類型的參數(shù),用于響應(yīng)HTTP訪問認(rèn)證請(qǐng)求的用戶名。
19.password:
要求為String類型的參數(shù),用于響應(yīng)HTTP訪問認(rèn)證請(qǐng)求的密碼。
20.processData:
要求為Boolean類型的參數(shù),默認(rèn)為true。默認(rèn)情況下,發(fā)送的數(shù)據(jù)將被轉(zhuǎn)換為對(duì)象(從技術(shù)角度來講并非字符串)以配合默認(rèn)內(nèi)容類型"application/x-www-form-urlencoded"。如果要發(fā)送DOM樹信息或者其他不希望轉(zhuǎn)換的信息,請(qǐng)?jiān)O(shè)置為false。
21.scriptCharset:
要求為String類型的參數(shù),只有當(dāng)請(qǐng)求時(shí)dataType為"jsonp"或者"script",并且type是GET時(shí)才會(huì)用于強(qiáng)制修改字符集(charset)。通常在本地和遠(yuǎn)程的內(nèi)容編碼不同時(shí)使用。
案例代碼:
$(function(){
$('#send').click(function(){
$.ajax({
type: "GET",
url: "test.json",
data: {username:$("#username").val(), content:$("#content").val()},
dataType: "json",
success: function(data){
$('#resText').empty(); //清空resText里面的所有內(nèi)容
var html='';
$.each(data, function(commentIndex, comment){
html +='<div class="comment"><h6>' + comment['username']
+ ':</h6><p class="para"' + comment['content']
+ '</p></div>';
});
Query的ajax請(qǐng)求
因?yàn)槭前l(fā)送 ajax 請(qǐng)求,不是操作DOM
不需要依賴選擇器去獲取到元素
他的使用是直接依賴 jQuuery 或者 $ 變量來使用
語法:$.ajax( { 本次發(fā)送ajax的配置項(xiàng) } )
配置項(xiàng)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
$.ajax({
url:'haha.php',
success:function(res){
//res 接受的就是后端給回的相應(yīng)結(jié)果
console.log(res)
},
error:function(){
console.log('請(qǐng)求失敗')
}
})
</script>
</body>
</html>
以上就是jQuery的ajax請(qǐng)求了
*請(qǐng)認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。