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)求
一、AJax的請(qǐng)求
ajax請(qǐng)求參數(shù):
1.url:
要求為String類型的參數(shù),(默認(rèn)為當(dāng)前頁(yè)地址)發(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í)使用。
示例前準(zhǔ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; }
}
}
新建ResultToJson類(將結(jié)果轉(zhuǎn)換為json類型)參考http://www.cnblogs.com/chenwolong/p/6020345.html
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;
}
}
新建JsonHelper類,參考http://www.cnblogs.com/chenwolong/p/JSON.html
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);
}
}
}
二、Get
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);
}
});
});
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);
}
});
});
傳遞實(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)鍵字。
三、Post
post請(qǐng)求原理和get請(qǐng)求不一樣,get請(qǐng)求的參數(shù)是通過url來傳遞的,而post請(qǐng)求則是通過http的請(qǐng)求體中傳過來的,WebApi的post請(qǐng)求也需要從http的請(qǐng)求體里面去取參數(shù)。說白了Get請(qǐng)求是通過URL傳遞一組鍵值對(duì),Post請(qǐng)求是發(fā)送一個(gè)Http請(qǐng)求體。Get請(qǐng)求,我們用[FromUri]關(guān)鍵字,Post請(qǐng)求,我們將使用另一個(gè)關(guān)鍵字[FromBoay]。
1、不傳參數(shù)的Post請(qǐng)求如下:
/// <summary>
/// 簡(jiǎn)單測(cè)試案例
/// </summary>
/// <returns></returns>
[HttpPost]
public string Get()
{
return "OK";
}
//無參數(shù)請(qǐng)求-簡(jiǎn)單示例
$(document).ready(function () {
$.ajax({
url: "http://localhost:9953/api/Person/Get",
type: "post",
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>
[HttpPost]
public string GetById([FromBody]int Id)
{
list = list.Where(p => p.Id == Id).ToList();
return JsonHelper.JsonSerializer<List<Person>>(list);
}
//單個(gè)參數(shù)傳遞- data: {"":"3"}, 這種方式也竟然正確
$(document).ready(function (data) {
$.ajax({
url: "http://localhost:9953/api/Person/GetById",
type: "post",
contentType: "application/json",
dataType: "text",
data: {Id:"3"},
success: function (result,status) {
alert(result)
},
error: function (error) {
alert(error);
}
});
});
3、傳遞多個(gè)參數(shù)如下:
//多個(gè)參數(shù)傳遞
$(document).ready(function (data) {
$.ajax({
url: "http://localhost:9953/api/Person/GetByIdAndSex",
type: "post",
contentType: "application/json",
dataType: "text",
data: JSON.stringify({ Id: "3",Sex:"W" }),
success: function (result, status) {
alert(result)
},
error: function (error) {
alert(error);
}
});
});
[HttpPost]
public HttpResponseMessage GetByIdAndSex([FromBody]dynamic Json)
{
string Id = Json.Id;
string Sex = Json.Sex;
List<Person> list_2 = new List<Person>();
var Result = from r in list
where r.Id == Convert.ToInt32(Id) && r.Sex == Sex
select r;
foreach (var Item in Result)
{
list_2.Add(Item);
}
return ResultToJson.toJson(list_2);
}
4、傳遞一個(gè)對(duì)象數(shù)據(jù)
//傳遞對(duì)象數(shù)組
$(document).ready(function (data) {
var dataList = [{ Id: "8888", Sex: "男", Name: "陳臥龍", Age: "26" },
{ Id: "8887", Sex: "男", Name: "陳大龍", Age: "27" },
{ Id: "8886", Sex: "男", Name: "陳小龍", Age: "25" }];
$.ajax({
url: "http://localhost:9953/api/Person/GetByObjectList",
type: "post",
contentType: "application/json",
dataType: "text",
data: JSON.stringify(dataList),
success: function (result, status) {
alert(result)
},
error: function (error) {
alert(error);
}
});
});
/// <summary>
/// 對(duì)象數(shù)組作為參數(shù)
/// </summary>
/// <param name="P"></param>
/// <returns></returns>
[HttpPost]
public HttpResponseMessage GetByObjectList([FromBody]dynamic Plist)
{
List<Person> list = new List<Person>();
foreach (var item in Plist)
{
Person person = new Person()
{
Name = item.Name,
Sex = item.Sex,
Id = item.Id,
Age = item.Age,
};
list.Add(person);
}
return ResultToJson.toJson(list);
}
四大請(qǐng)求:Get,Post,Put,Delete ,其中Put、delete請(qǐng)求都是采用的Post請(qǐng)求原理,他們直接大同小異,無非就是Put請(qǐng)求做修改 插入,Delete請(qǐng)求作刪除。因此:Put Delete 請(qǐng)求均可采用本文中的請(qǐng)求方式,只是他們所作的動(dòng)作不一樣罷了!
轉(zhuǎn)載自:https://www.cnblogs.com/chenwolong/
原作者:天才臥龍