1.首先建一個(gè)WebService程序
/// <summary>/// WebService1 的摘要說(shuō)明/// </summary>[WebService(Namespace = "http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)][ToolboxItem(false)]// 若要允許使用 ASP.NET AJAX 從腳本中調(diào)用此 Web 服務(wù),請(qǐng)取消對(duì)下行的注釋。[System.Web.Script.Services.ScriptService]public class WebService1 : System.Web.Services.WebService{ [WebMethod] public string HelloWorld() { CommonData.Json.ObjectSerialization ser = new CommonData.Json.ObjectSerialization(); Student stu = new Student(); stu.Id = 1; stu.Name = "hechen"; string json = ser.EntityToJson(stu); return json; }}[System.Web.Script.Services.ScriptService] 這里得注意,默認(rèn)情況下這個(gè)特性是注釋起來(lái)的,如果想用Javascript來(lái)調(diào)用WebService 就要取消這個(gè)注釋
WebService 的內(nèi)容不必多說(shuō),用Jquery調(diào)用WebService 返回肯定是一個(gè)xml。而xml是說(shuō)明文件,而不是具體方法返回的值,所以我們做適當(dāng)?shù)奶幚怼N覀冞@里WebService方法返回的是JSON數(shù)據(jù),以便在前臺(tái)解析。下載是實(shí)體類(lèi)序列化JSON的代碼。
2. 實(shí)體對(duì)象序列化JSON
/** * * 2009-5-26 * 賀 臣 * * 將某個(gè)對(duì)象轉(zhuǎn)化為Json數(shù)據(jù)格式 * */using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;using System.Data;using System.ServiceModel.Web;using System.Runtime.Serialization;using System.Runtime.Serialization.Json;namespace CommonData.Json{ public class ObjectSerialization { private object _entity; /// <summary> /// 被序列化得實(shí)體對(duì)象 /// </summary> public object Entity { get { return _entity; } set { _entity = value; } } private string _jsonData; /// <summary> /// 被轉(zhuǎn)化為json格式數(shù)據(jù)的對(duì)象 /// </summary> public string JsonData { get { return _jsonData; } set { _jsonData = value; } } /// <summary> /// 無(wú)參數(shù)構(gòu)造方法 /// </summary> public ObjectSerialization() { } /// <summary> /// 有參數(shù)構(gòu)造方法 /// </summary> /// <param name="entity">要被序列化得實(shí)體對(duì)象</param> public ObjectSerialization(object entity) { this._entity = entity; } /// <summary> /// 序列化實(shí)體對(duì)象 /// </summary> /// <returns></returns> public string EntityToJson() { var serializer = new DataContractJsonSerializer(Entity.GetType()); MemoryStream ms = new MemoryStream(); serializer.WriteObject(ms, Entity); byte[] myByte = new byte[ms.Length]; ms.Position = 0; ms.Read(myByte, 0, (int)ms.Length); string dataString = Encoding.UTF8.GetString(myByte); return dataString; } /// <summary> /// 序列化實(shí)體對(duì)象 /// </summary> /// <param name="entity">要被序列化得實(shí)體對(duì)象</param> /// <returns></returns> public string EntityToJson(object entity) { this._entity = entity; return EntityToJson(); } /// <summary> /// 將Json格式數(shù)據(jù)轉(zhuǎn)換為對(duì)象 /// </summary> /// <returns></returns> public T GetObjectJson<T>() { MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(JsonData)); var serializer = new DataContractJsonSerializer(typeof(T)); T t = (T)serializer.ReadObject(ms); return t; } /// <summary> /// 將Json格式數(shù)據(jù)轉(zhuǎn)換為對(duì)象 /// </summary> /// <param name="jsonData">json數(shù)據(jù)格式</param> /// <returns></returns> public T GetObjectJson<T>(string jsonData) { this._jsonData = jsonData; return GetObjectJson<T>(); } }}注意序列化實(shí)體必須用可序列化特性修飾,如Serialiable,否則它不能序列化為JSON數(shù)據(jù)字符串
3.前臺(tái)程序Jquery調(diào)用
<script src="jquery-1[1].2.3.min.js" type="text/javascript"></script><script src="json2.js" type="text/javascript"></script><script type="text/javascript"> $(document).ready(function() { $("#btnClick").click(function() { $.ajax({ url:"http://localhost:10168/WebService1.asmx/HelloWorld", beforeSend: function(x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); }, data:{}, dataType:"json", type:"POST", error: function(x, e) { alert(x.responseText); }, complete: function(x) { //alert(x.responseText); } , success:function(data){ var msg=data.d; var json=JSON2.parse(msg); alert(json.id); } }); }); });</script>這里進(jìn)入了Jquery的核心文件和一個(gè)JSON2.js文件
url:"http://localhost:10168/WebService1.asmx/HelloWorld" 這個(gè)是調(diào)用WebService方法的路徑,HelloWorld 是WebService 中的方法。
同時(shí)還要設(shè)置WebService請(qǐng)求后返回的參數(shù)格式(json),data是用于解釋返回的值。這里值得注意的是data是一個(gè)json格式的字符串,而且對(duì)象名為d,所以我們用到了后面的var msg=data.d;
如果我們要能夠像JSON那個(gè)以 . 操作來(lái)訪問(wèn)鍵值,我們就使用到了 JSON2.js 中的方法將 json字符串轉(zhuǎn)化為json對(duì)象,這樣就可以以. 操作來(lái)訪問(wèn)對(duì)象了。
如果我們需要調(diào)用帶參數(shù)的WebService ,則我們可以再data 中指定傳遞的參數(shù),參數(shù)名要和WebService中方法參數(shù)名相同。
在這里應(yīng)該說(shuō)是沒(méi)有問(wèn)題,我在寫(xiě)這個(gè)例子的時(shí)候,并不是這么順利,后來(lái)查了很多關(guān)于WebService的資料,原來(lái)我們要修改WebService中Web.config 的配置,否則我們不能以Url 那種格式訪問(wèn)WebService。
配置如下:
在System.web 這個(gè)節(jié)點(diǎn)中添加如下配置即可
<webServices> <protocols> <add name="HttpGet"/> <add name="HttpPost"/> </protocols></webServices>
以上就是本文的全部?jī)?nèi)容,希望能給大家一個(gè)參考,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注