jquery中的Ajax方法參數(shù)總是記不住,這里記錄一下。
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í)使用。
以上便是Ajax請(qǐng)求各參數(shù)介紹
下面開始咱們的AJax請(qǐng)求之Get方式
Get請(qǐng)求就是通過URL地址進(jìn)行的請(qǐng)求,其有如下特點(diǎn):
1、Get請(qǐng)求的安全性不如Post
2、Get請(qǐng)求允許傳遞的數(shù)據(jù)量為1024字節(jié),因此:不宜傳遞過多數(shù)據(jù),否則會(huì)超出限制
3、Get請(qǐng)求時(shí),將各個(gè)參數(shù)浮在URL之后進(jìn)行請(qǐng)求,也就是將數(shù)據(jù)放在Http協(xié)議頭中
下面來簡(jiǎn)單介紹下幾種不同的Get請(qǐng)求
1、不傳遞參數(shù)的Get請(qǐng)求
2、傳遞一個(gè)參數(shù)的Get請(qǐng)求
3、傳遞多個(gè)參數(shù)的Get請(qǐng)求
4、傳遞一個(gè)實(shí)體的Get請(qǐng)求
在進(jìn)行之前,先來做下準(zhǔn)備工作(本案例并沒有做到真正的數(shù)據(jù)持久化,僅僅為簡(jiǎn)單模擬而已):
首先建一個(gè)Person類,如下:

public class Person { private int id; public int Id { get { return id; } set { id = value; } } private int age; public int Age { get { return age; } set { age = value; } } private string name; public string Name { get { return name; } set { name = value; } } private string sex; public string Sex { get { return sex; } set { sex = value; } } }
很簡(jiǎn)單,不多說。
另一個(gè)ResultToJson類,如下:<我之前的博客中有專門描述,請(qǐng)參照我的博客:C# web api 返回類型設(shè)置為json的兩種方法>
如下:

public class ResultToJson { public static HttpResponseMessage toJson(Object obj) { String str; if (obj is String || obj is Char) { str = obj.ToString(); } else { JavascriptSerializer serializer = new JavaScriptSerializer(); str = serializer.Serialize(obj); } HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; return result; } }
最后一個(gè)就是JsonHelper類,這個(gè)大家可參考我之前的博客:C#處理JSON數(shù)據(jù)
至此:準(zhǔn)備工作準(zhǔn)備完畢
新建一個(gè)WebApi控制器如下:

public class PersonController : ApiController { List<Person> list = new List<Person>(); /// <summary> /// 初始化數(shù)據(jù) /// </summary> public PersonController() { for (int i = 0; i < 100; i++) { Person P = new Person() { Id = i, Name = "Name" + i, Age = i, Sex = i % 2 == 0 ? "M" : "W" }; list.Add(P); } } }
1、不傳參數(shù)的Get請(qǐng)求如下:

/// <summary> /// 簡(jiǎn)單測(cè)試案例 /// </summary> /// <returns></returns> [HttpGet] public string Get() { return "OK"; }

//無參數(shù)請(qǐng)求-簡(jiǎn)單示例 $(document).ready(function () { $.ajax({ url: "http://localhost:9953/api/Person/Get", type: "get", contentType: "application/json", dataType: "text", data:{}, success: function (result,status) { if (status == "success") { alert(result); } }, error: function (error) { alert(error); } }); });
2、傳遞一個(gè)參數(shù)的案例如下:

/// <summary> /// 通過id獲取特定數(shù)據(jù) /// </summary> /// <param name="Id"></param> /// <returns></returns> [HttpGet] public string GetById(int Id) { list = list.Where(p => p.Id == Id).ToList(); return JsonHelper.JsonSerializer<List<Person>>(list); }

//單個(gè)參數(shù)傳遞 $(document).ready(function (data) { $.ajax({ url: "http://localhost:9953/api/Person/GetById", type: "get", dataType: "text", data: {Id:"3"}, success: function (result,status) { alert(result) }, error: function (error) { alert(error); } }); });
有興趣的小虎斑們也可以嘗試URL傳參的方法:<把請(qǐng)求的data去掉,URL后面加上傳遞的參數(shù)>

//單個(gè)參數(shù)傳遞 $(document).ready(function (data) { $.ajax({ url: "http://localhost:9953/api/Person/GetById?Id=3", type: "get", dataType: "text", success: function (result,status) { alert(result) }, error: function (error) { alert(error); } }); });
3、傳遞多個(gè)參數(shù)如下:

/// <summary> /// 多個(gè)參數(shù)傳遞 /// </summary> /// <param name="Name"></param> /// <returns></returns> [HttpGet] public HttpResponseMessage GetByIdAndSex(int Id,string Sex) { List<Person> list_2 = new List<Person>(); var Result = from r in list where r.Id == Id && r.Sex==Sex select r; foreach (var Item in Result) { list_2.Add(Item); } return ResultToJson.toJson(list_2); }

//多個(gè)參數(shù)傳遞 $(document).ready(function (data) { $.ajax({ url: "http://localhost:9953/api/Person/GetByIdAndSex", type: "get", contentType: "application/json", dataType: "text", data: { Id: "3",Sex:"W" }, success: function (result, status) { alert(result) }, error: function (error) { alert(error); } }); });
當(dāng)然,有興趣的小虎斑也可以將參數(shù)放在URL后面進(jìn)行測(cè)試,在此不作說明!
4、傳遞一個(gè)實(shí)體

/// <summary> /// 對(duì)象作為參數(shù) /// </summary> /// <param name="P"></param> /// <returns></returns> [HttpGet] public HttpResponseMessage GetByObject([FromUri]Person P) { return ResultToJson.toJson(P); }

//傳遞一個(gè)對(duì)象該如何? $(document).ready(function (data) { $.ajax({ url: "http://localhost:9953/api/Person/GetByObject", type: "get", dataType: "text", data: { Id: "8888",Sex:"男",Name:"陳臥龍",Age:"26" }, success: function (result, status) { alert(result) }, error: function (error) { alert(error); } }); });
大家可能發(fā)現(xiàn)傳遞實(shí)體時(shí),代碼和上述有點(diǎn)不同,GetByObject([FromUri]Person P)加了一個(gè)[FromUri]。如果不加上這個(gè)關(guān)鍵詞的話,那么則會(huì)傳遞實(shí)體失敗,究其原因如下:
還記得有面試題問過get和post請(qǐng)求的區(qū)別嗎?其中有一個(gè)區(qū)別就是get請(qǐng)求的數(shù)據(jù)會(huì)附在URL之后(就是把數(shù)據(jù)放置在HTTP協(xié)議頭中),而post請(qǐng)求則是放在http協(xié)議包的包體中。
如果大家不加上[FromUri]關(guān)鍵字,Get請(qǐng)求時(shí)URL會(huì)被解析為:http://localhost:9953/api/Person/GetByObject?Id=8888&Sex=男&Name=陳臥龍&Age=26,當(dāng)被解析成這種格式后,Net后端的webApi是無法解析成實(shí)體對(duì)象的。因此,在傳遞一個(gè)對(duì)象時(shí),我們有必要加上[FromUri]關(guān)鍵字。
其實(shí):在所有的Get請(qǐng)求時(shí),我建議大家都加上[FromUri]關(guān)鍵字,這樣就不會(huì)引發(fā)諸如上述的問題。再說了,養(yǎng)成一個(gè)好的習(xí)慣不是挺好的么?
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注