Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
日常工作中(主要使用ASP.net),我需要編寫很多JavaScript代碼。我做的最重復的任務之一是jQuery Ajax調用。你看:
$.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
}
});
我不知道對您來說是否相同,但是對我來說用這種語法編寫調用太麻煩了。而且,以前必須按照已知規則使用參數構建字符串以傳遞給WebMethod:字符串必須用引號傳遞,數字不能傳遞,等等。
因此,我決定創建一個小而有用的JavaScript類來幫助我有了這個特定的問題,現在我已經完成了jQuery Ajax調用,這對我來說非常友好。
在類構造函數中,我傳遞頁面名稱,方法名稱以及成功和錯誤函數。以后,我會根據需要對addParam方法進行盡可能多的調用。最后,我調用run方法進行Ajax調用。成功函數和錯誤函數必須分別編寫。
參數根據其類型進行處理。如果參數是字符串,則使用引號。如果是數字,我不會。日期參數是一種特殊情況。在這種情況下,我使用JavaScript日期對象的getTime()函數,該函數給了我自1970年1月1日以來的日期的毫秒數。后來,我將該值轉換為UTC時間,這樣我得到了一個最終的毫秒數,即我可以將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) {
}
另外一個好處是,您可以將成功和錯誤功能重新用于幾個ajax調用。
希望對您有幫助??!隨時在您的應用程序中使用jAjax類。
JAX 是一種與服務器交換數據的技術,可以在補充在整個頁面的情況下更新網頁的一部分。接下來通過本文給大家介紹ajax一些常用方法,大家有需要可以一起學習。
1.url:
要求為String類型的參數,(默認為當前頁地址)發送請求的地址。
2.type:
要求為String類型的參數,請求方式(post或get)默認為get。注意其他http請求方法,例如put和delete也可以使用,但僅部分瀏覽器支持。
3.timeout:
要求為Number類型的參數,設置請求超時時間(毫秒)。此設置將覆蓋$.ajaxSetup()方法的全局設置。
4.async:
要求為Boolean類型的參數,默認設置為true,所有請求均為異步請求。如果需要發送同步請求,請將此選項設置為false。注意,同步請求將鎖住瀏覽器,用戶其他操作必須等待請求完成才可以執行。
5.cache:
要求為Boolean類型的參數,默認為true(當dataType為script時,默認為false),設置為false將不會從瀏覽器緩存中加載請求信息。
6.data:
要求為Object或String類型的參數,發送到服務器的數據。如果已經不是字符串,將自動轉換為字符串格式。get請求中將附加在url后。防止這種自動轉換,可以查看 processData選項。對象必須為key/value格式,例如{foo1:"bar1",foo2:"bar2"}轉換為&foo1=bar1&foo2=bar2。如果是數組,JQuery將自動為不同值對應同一個名稱。例如{foo:["bar1","bar2"]}轉換為&foo=bar1&foo=bar2。
7.dataType:
要求為String類型的參數,預期服務器返回的數據類型。如果不指定,JQuery將自動根據http包mime信息返回responseXML或responseText,并作為回調函數參數傳遞??捎玫念愋腿缦拢?/p>
xml:返回XML文檔,可用JQuery處理。
html:返回純文本HTML信息;包含的script標簽會在插入DOM時執行。
script:返回純文本JavaScript代碼。不會自動緩存結果。除非設置了cache參數。注意在遠程請求時(不在同一個域下),所有post請求都將轉為get請求。
json:返回JSON數據。
jsonp:JSONP格式。使用SONP形式調用函數時,例如myurl?callback=?,JQuery將自動替換后一個“?”為正確的函數名,以執行回調函數。
text:返回純文本字符串。
8.beforeSend:
要求為Function類型的參數,發送請求前可以修改XMLHttpRequest對象的函數,例如添加自定義HTTP頭。在beforeSend中如果返回false可以取消本次ajax請求。XMLHttpRequest對象是惟一的參數。
function(XMLHttpRequest){
this; //調用本次ajax請求時傳遞的options參數
}
9.complete:
要求為Function類型的參數,請求完成后調用的回調函數(請求成功或失敗時均調用)。參數:XMLHttpRequest對象和一個描述成功請求類型的字符串。
function(XMLHttpRequest, textStatus){
this; //調用本次ajax請求時傳遞的options參數
}
10.success:
要求為Function類型的參數,請求成功后調用的回調函數,有兩個參數。
(1)由服務器返回,并根據dataType參數進行處理后的數據。
(2)描述狀態的字符串。
function(data, textStatus){
//data可能是xmlDoc、jsonObj、html、text等等
this; //調用本次ajax請求時傳遞的options參數
}
11.error:
要求為Function類型的參數,請求失敗時被調用的函數。該函數有3個參數,即XMLHttpRequest對象、錯誤信息、捕獲的錯誤對象(可選)。ajax事件函數如下:
function(XMLHttpRequest, textStatus, errorThrown){
//通常情況下textStatus和errorThrown只有其中一個包含信息
this; //調用本次ajax請求時傳遞的options參數
}
12.contentType:
要求為String類型的參數,當發送信息至服務器時,內容編碼類型默認為"application/x-www-form-urlencoded"。該默認值適合大多數應用場合。
13.dataFilter:
要求為Function類型的參數,給Ajax返回的原始數據進行預處理的函數。提供data和type兩個參數。data是Ajax返回的原始數據,type是調用jQuery.ajax時提供的dataType參數。函數返回的值將由jQuery進一步處理。
function(data, type){
//返回處理后的數據
return data;
}
14.dataFilter:
要求為Function類型的參數,給Ajax返回的原始數據進行預處理的函數。提供data和type兩個參數。data是Ajax返回的原始數據,type是調用jQuery.ajax時提供的dataType參數。函數返回的值將由jQuery進一步處理。
function(data, type){
//返回處理后的數據
return data;
}
15.global:
要求為Boolean類型的參數,默認為true。表示是否觸發全局ajax事件。設置為false將不會觸發全局ajax事件,ajaxStart或ajaxStop可用于控制各種ajax事件。
16.ifModified:
要求為Boolean類型的參數,默認為false。僅在服務器數據改變時獲取新數據。服務器數據改變判斷的依據是Last-Modified頭信息。默認值是false,即忽略頭信息。
17.jsonp:
要求為String類型的參數,在一個jsonp請求中重寫回調函數的名字。該值用來替代在"callback=?"這種GET或POST請求中URL參數里的"callback"部分,例如{jsonp:'onJsonPLoad'}會導致將"onJsonPLoad=?"傳給服務器。
18.username:
要求為String類型的參數,用于響應HTTP訪問認證請求的用戶名。
19.password:
要求為String類型的參數,用于響應HTTP訪問認證請求的密碼。
20.processData:
要求為Boolean類型的參數,默認為true。默認情況下,發送的數據將被轉換為對象(從技術角度來講并非字符串)以配合默認內容類型"application/x-www-form-urlencoded"。如果要發送DOM樹信息或者其他不希望轉換的信息,請設置為false。
21.scriptCharset:
要求為String類型的參數,只有當請求時dataType為"jsonp"或者"script",并且type是GET時才會用于強制修改字符集(charset)。通常在本地和遠程的內容編碼不同時使用。
案例代碼:
$(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里面的所有內容
var html='';
$.each(data, function(commentIndex, comment){
html +='<div class="comment"><h6>' + comment['username']
+ ':</h6><p class="para"' + comment['content']
+ '</p></div>';
});
Query的ajax請求
因為是發送 ajax 請求,不是操作DOM
不需要依賴選擇器去獲取到元素
他的使用是直接依賴 jQuuery 或者 $ 變量來使用
語法:$.ajax( { 本次發送ajax的配置項 } )
配置項
<!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 接受的就是后端給回的相應結果
console.log(res)
},
error:function(){
console.log('請求失敗')
}
})
</script>
</body>
</html>
以上就是jQuery的ajax請求了
*請認真填寫需求信息,我們會在24小時內與您取得聯系。