本文實(shí)例講述了jQuery調(diào)用Webservice傳遞json數(shù)組的方法。分享給大家供大家參考,具體如下:
Jquery由于提供的$.ajax強(qiáng)大方法,使得其調(diào)用webservice實(shí)現(xiàn)異步變得簡(jiǎn)單起來(lái),可以在頁(yè)面上傳遞Json字符串到Webservice中,Webservice方法進(jìn)行業(yè)務(wù)處理后,返回Json對(duì)象給頁(yè)面,讓頁(yè)面去展現(xiàn)。
這一切都非常的簡(jiǎn)單,今天要學(xué)習(xí)的并非這些。我們?cè)趯?shí)際處理業(yè)務(wù)過(guò)程中,會(huì)發(fā)現(xiàn)往往頁(yè)面要傳遞給webservice 的并非一個(gè)或多個(gè)字符串,有時(shí)候需要傳遞的是一個(gè)組合數(shù)據(jù),如這樣的一組數(shù)據(jù):
客戶端將這樣的Json字符串作為$.ajax方法的data參數(shù)是沒(méi)有問(wèn)題的,然而,服務(wù)端的webservice該如何去寫(xiě)接收參數(shù)卻成為了一個(gè)問(wèn)題。在百度、谷歌了一番后,只發(fā)現(xiàn)提問(wèn)的卻沒(méi)有回答的。索性還是自己去研究吧,發(fā)現(xiàn)其實(shí)Employee對(duì)象首先是一個(gè)數(shù)組,其次數(shù)組的每一項(xiàng)都是一個(gè)Dictionary<string,string>字典類(lèi)型。于是我嘗試在服務(wù)端使用Dictionary<string,string>[] Employee來(lái)接收客戶端傳遞的參數(shù),一切如我所料,成功!
客戶端代碼如下:
//JQuery 調(diào)用webService導(dǎo)入數(shù)據(jù)function LoadData() { var studentData = CollectionData(); $.ajax({ url: "ImportDataService.asmx/ImportStu", type: "post", contentType: "application/json;charset=utf-8", dataType: "json", data: "{'students':[{'name':'KoBe ','sex':'boy','age':'20'},{'name':'Mary','sex':'girl','age':'19'}]}", success: function(result) { alert(result.d); }, error: function(e) { alert(e.responseText); } });}
服務(wù)端代碼如下:
/// <summary>////// </summary>/// <param name="students"></param>/// <returns></returns>[WebMethod][ScriptMethod(ResponseFormat=ResponseFormat.Json)]public string ImportStu(Dictionary<string,string> []students){ if (students.Length == 0) { return "沒(méi)有任何數(shù)據(jù)!"; } else { try { foreach (Dictionary<string, string> stu in students) { //構(gòu)造一個(gè)新的Student對(duì)象。 Student student = new Student(); //為新構(gòu)造的Student對(duì)象屬性賦值。 foreach (string key in stu.Keys) { switch (key) { case "name": student.Name = stu[key]; break; case "sex": student.Sex = stu[key]; break; case "age": int age; if (Int32.TryParse(stu[key], out age)) { student.Age = age; } else { student.Age = 0; } break; default: break; } } } return "導(dǎo)入學(xué)生成功!"; } catch { throw new Exception("導(dǎo)入學(xué)生失敗!"); } }}
需要注意的是,服務(wù)端參數(shù)名需要和客戶端Json數(shù)組的key值相同,如上代碼中,參數(shù)名都為students。
更多關(guān)于jQuery相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《jQuery擴(kuò)展技巧總結(jié)》、《jQuery常用插件及用法總結(jié)》、《jQuery拖拽特效與技巧總結(jié)》、《jQuery表格(table)操作技巧匯總》、《jquery中Ajax用法總結(jié)》、《jQuery常見(jiàn)經(jīng)典特效匯總》、《jQuery動(dòng)畫(huà)與特效用法總結(jié)》及《jquery選擇器用法總結(jié)》
希望本文所述對(duì)大家jQuery程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注