開發環境: Visual Studio 2005 SP1
部署環境:Windows Server 2008 r2 + IIS 7
1.建立資料來源項目CrossDomain
主要檔案如下:
1.Handler.ashx
作為jquery跨域請求*.handler的響應,代碼如下:
using System;<br />using System.Collections.Generic;<br />using System.Web;<br />using System.Web.Services;<br />namespace CrossDomain<br />{<br /> /// <summary><br /> /// $codebehindclassname$ 的摘要說明<br /> /// </summary><br /> [WebService(Namespace = "http://tempuri.org/")]<br /> [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]<br /> public class Handler : IHttpHandler<br /> {<br /> public void ProcessRequest(HttpContext context)<br /> {<br /> context.Response.ContentType = "text/plain";<br /> string callbackMethodName = context.Request.Params["jsoncallback"];<br /> string currentCity = context.Request["city"];<br /> currentCity = string.IsNullOrEmpty(currentCity) ? "北京" : "瀋陽";<br /> string result = callbackMethodName + "({/"city/":" + "/"" + currentCity + "/", /"dateTime/":" + "/"" + DateTime.Now + "/"});";<br /> context.Response.Write(result);<br /> }<br /> public bool IsReusable<br /> {<br /> get<br /> {<br /> return false;<br /> }<br /> }<br /> }<br />}<br />
2.WebService.asmx
作為jquery跨域請求WebService的響應,代碼如下:
using System;<br />using System.Collections.Generic;<br />using System.Web;<br />using System.Web.Services;<br />namespace CrossDomain<br />{<br /> /// <summary><br /> /// WebService 的摘要說明<br /> /// </summary><br /> [WebService(Namespace = "http://tempuri.org/")]<br /> [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]<br /> [System.ComponentModel.ToolboxItem(false)]<br /> public class WebService : System.Web.Services.WebService<br /> {<br /> [WebMethod]<br /> public void HelloWorld(string city)<br /> {<br /> string callbackMethodName = HttpContext.Current.Request.Params["jsoncallback"] ?? "";<br /> city = string.IsNullOrEmpty(city) ? "北京" : "瀋陽";<br /> string result = callbackMethodName + "({/"city/":" + "/"" + city + "/", /"dateTime/":" + "/"" + DateTime.Now + "/"});";<br /> HttpContext.Current.Response.Write(result);<br /> HttpContext.Current.Response.End();<br /> }<br /> [WebMethod]<br /> public void ws(string name, string time)<br /> {<br /> HttpRequest Request = HttpContext.Current.Request;<br /> string callback = Request["callback"];<br /> HttpResponse Response = HttpContext.Current.Response;<br /> Response.Write(callback + "({msg:'this is" + name + "jsonp'})");<br /> Response.End();<br /> }<br /> }<br />}<br />
3.Web.config
需要修改web.config檔案,注意webServices
節(這是請求webservice擷取資料的關鍵)
具體如下:
<?xml version="1.0" encoding="utf-8"?><br /><configuration></p><p> <appSettings/><br /> <connectionStrings/></p><p> <system.web><br /> <!--<br /> 設定 compilation debug="true" 可將偵錯符號插入<br /> 已編譯的頁面中。但由於這會<br /> 影響效能,因此只在開發過程中將此值<br /> 設定為 true。<br /> --><br /> <compilation debug="false"><br /> </compilation><br /> <!--<br /> 通過 <authentication> 節可以配置 ASP.NET 用來<br /> 識別進入使用者的<br /> 安全身分識別驗證模式。<br /> --><br /> <authentication mode="Windows" /><br /> <!--<br /> 如果在執行請求的過程中出現未處理的錯誤,<br /> 則通過 <customErrors> 節可以配置相應的處理步驟。具體說來,<br /> 開發人員通過該節可以配置<br /> 要顯示的 html 錯誤頁<br /> 以代替錯誤堆疊追蹤。<br /> <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"><br /> <error statusCode="403" redirect="NoAccess.htm" /><br /> <error statusCode="404" redirect="FileNotFound.htm" /><br /> </customErrors><br /> --><br /> <webServices><br /> <protocols><br /> <add name="HttpGet"/><br /> <add name="HttpPost"/><br /> </protocols><br /> </webServices><br /> </system.web><br /></configuration><br />
2.建立跨域請求測試專案CrossDomainRequestTest
主要檔案如下:
1.CrossDomainRequestHandler.htm
跨域請求*.handler擷取josn格式資料測試頁,代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><br /><html xmlns="http://www.w3.org/1999/xhtml" ><br /><head><br /> <title></title><br /> <mce:script type="text/javascript" language="javascript" src="js/jquery-1.4.4.js" mce_src="js/jquery-1.4.4.js"></mce:script><br /> <mce:script type="text/javascript" language="javascript" src="js/jquery-1.4.4.js" mce_src="js/jquery-1.4.4.js"></mce:script><br /> <mce:script type="text/javascript" language="javascript"><!--<br /> $(document).ready(function() {<br />// var clientUrl = "http://localhost:4508/Handler.ashx?jsoncallback=?";<br /> var clientUrl = "http://192.168.120.179:8086/Handler.ashx?jsoncallback=?"<br /> var currentCity = "哈爾濱";<br /> $.ajax({<br /> url: clientUrl,<br /> dataType: "jsonp",<br /> data : {city : currentCity},<br /> success : OnSuccess,<br /> error : OnError<br /> });<br /> });<br /> function OnSuccess(json) {<br /> $("#data").html("城市:" + json.city + ",時間:" + json.dateTime);<br /> }<br /> function OnError(XMLHttpRequest, textStatus, errorThrown) {<br /> targetDiv = $("#data");<br /> if (errorThrown || textStatus == "error" || textStatus == "parsererror" || textStatus == "notmodified") {<br /> targetDiv.replaceWith("請求資料時發生錯誤!");<br /> return;<br /> }<br /> if (textStatus == "timeout") {<br /> targetDiv.replaceWith("請求資料逾時!");<br /> return;<br /> }<br /> }</p><p>// --></mce:script><br /></head><br /><body><br /><div id="data"></div><br /></body><br /></html>
2.CrossDomainRequestWebService.htm
跨域請求WebService *.asmx
擷取josn格式資料測試頁,代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><br /><html xmlns="http://www.w3.org/1999/xhtml" ><br /><head><br /> <title></title><br /> <mce:script type="text/javascript" language="javascript" src="js/jquery-1.4.4.js" mce_src="js/jquery-1.4.4.js"></mce:script><br /> <mce:script type="text/javascript" language="javascript"><!--<br /> $(document).ready(function() {<br />// var clientUrl = "http://localhost:4508/WebService.asmx/HelloWorld?jsoncallback=?";<br /> var clientUrl = "http://192.168.120.179:8086/WebService.asmx/HelloWorld?jsoncallback=?";<br /> var currentCity = "哈爾濱";<br /> $.getJSON(<br /> clientUrl,<br /> { city: currentCity },<br /> function(json) {<br /> $("#data").html("城市:" + json.city + ",時間:" + json.dateTime);<br /> }<br /> );<br /> });<br /> function OnSuccess(responseData) {<br /> $("#data").html(responseData.city);<br /> }<br /> function OnError(XMLHttpRequest, textStatus, errorThrown) {<br /> targetDiv = $("#data");<br /> if (errorThrown || textStatus == "error" || textStatus == "parsererror" || textStatus == "notmodified") {<br /> targetDiv.replaceWith("請求資料時發生錯誤!");<br /> return;<br /> }<br /> if (textStatus == "timeout") {<br /> targetDiv.replaceWith("請求資料逾時!");<br /> return;<br /> }<br /> }</p><p>// --></mce:script><br /></head><br /><body><br /><div id="data"></div><br /></body><br /></html><br />
3.結果:
城市:瀋陽,時間:2011/5/18 14:49:37