利用JQuery jsonp实现Ajax跨域请求 .Net 的*.handler 和 WebService,返回json数据
生活随笔
收集整理的這篇文章主要介紹了
利用JQuery jsonp实现Ajax跨域请求 .Net 的*.handler 和 WebService,返回json数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原文:? http://blog.csdn.net/polarissky/article/details/6429554
1.新建數據源項目CrossDomain
??? 主要文件如下:
?? 1.Handler.ashx? 作為jquery跨域請求*.handler的響應,代碼如下:
??? using System; using System.Collections.Generic; using System.Web; using System.Web.Services; namespace CrossDomain { /// <summary> /// $codebehindclassname$ 的摘要說明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string callbackMethodName = context.Request.Params["jsoncallback"]; string currentCity = context.Request["city"]; currentCity = string.IsNullOrEmpty(currentCity) ? "北京" : "沈陽"; string result = callbackMethodName + "({/"city/":" + "/"" + currentCity + "/", /"dateTime/":" + "/"" + DateTime.Now + "/"});"; context.Response.Write(result); } public bool IsReusable { get { return false; } } } }? 2.WebService.asmx? 作為jquery跨域請求WebService的響應,代碼如下:
? using System; using System.Collections.Generic; using System.Web; using System.Web.Services; namespace CrossDomain { /// <summary> /// WebService 的摘要說明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] public class WebService : System.Web.Services.WebService { [WebMethod] public void HelloWorld(string city) { string callbackMethodName = HttpContext.Current.Request.Params["jsoncallback"] ?? ""; city = string.IsNullOrEmpty(city) ? "北京" : "沈陽"; string result = callbackMethodName + "({/"city/":" + "/"" + city + "/", /"dateTime/":" + "/"" + DateTime.Now + "/"});"; HttpContext.Current.Response.Write(result); HttpContext.Current.Response.End(); } [WebMethod] public void ws(string name, string time) { HttpRequest Request = HttpContext.Current.Request; string callback = Request["callback"]; HttpResponse Response = HttpContext.Current.Response; Response.Write(callback + "({msg:'this is" + name + "jsonp'})"); Response.End(); } } }
? 3.Web.config 需要修改web.config文件,注意webServices節(這是請求webservice獲取數據的關鍵)具體如下:
? <?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings/> <connectionStrings/> <system.web> <!-- 設置 compilation debug="true" 可將調試符號插入 已編譯的頁面中。但由于這會 影響性能,因此只在開發過程中將此值 設置為 true。 --> <compilation debug="false"> </compilation> <!-- 通過 <authentication> 節可以配置 ASP.NET 用來 識別進入用戶的 安全身份驗證模式。 --> <authentication mode="Windows" /> <!-- 如果在執行請求的過程中出現未處理的錯誤, 則通過 <customErrors> 節可以配置相應的處理步驟。具體說來, 開發人員通過該節可以配置 要顯示的 html 錯誤頁 以代替錯誤堆棧跟蹤。 <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> <error statusCode="403" redirect="NoAccess.htm" /> <error statusCode="404" redirect="FileNotFound.htm" /> </customErrors> --> <webServices> <protocols> <add name="HttpGet"/> <add name="HttpPost"/> </protocols> </webServices> </system.web> </configuration>?
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"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title></title> <mce:script type="text/javascript" language="javascript" src="js/jquery-1.4.4.js" mce_src="js/jquery-1.4.4.js"></mce:script> <mce:script type="text/javascript" language="javascript" src="js/jquery-1.4.4.js" mce_src="js/jquery-1.4.4.js"></mce:script> <mce:script type="text/javascript" language="javascript"><!-- $(document).ready(function() { // var clientUrl = "http://localhost:4508/Handler.ashx?jsoncallback=?"; var clientUrl = "http://192.168.120.179:8086/Handler.ashx?jsoncallback=?" var currentCity = "哈爾濱"; $.ajax({ url: clientUrl, dataType: "jsonp", data : {city : currentCity}, success : OnSuccess, error : OnError }); }); function OnSuccess(json) { $("#data").html("城市:" + json.city + ",時間:" + json.dateTime); } function OnError(XMLHttpRequest, textStatus, errorThrown) { targetDiv = $("#data"); if (errorThrown || textStatus == "error" || textStatus == "parsererror" || textStatus == "notmodified") { targetDiv.replaceWith("請求數據時發生錯誤!"); return; } if (textStatus == "timeout") { targetDiv.replaceWith("請求數據超時!"); return; } } // --></mce:script> </head> <body> <div id="data"></div> </body> </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"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title></title> <mce:script type="text/javascript" language="javascript" src="js/jquery-1.4.4.js" mce_src="js/jquery-1.4.4.js"></mce:script> <mce:script type="text/javascript" language="javascript"><!-- $(document).ready(function() { // var clientUrl = "http://localhost:4508/WebService.asmx/HelloWorld?jsoncallback=?"; var clientUrl = "http://192.168.120.179:8086/WebService.asmx/HelloWorld?jsoncallback=?"; var currentCity = "哈爾濱"; $.getJSON( clientUrl, { city: currentCity }, function(json) { $("#data").html("城市:" + json.city + ",時間:" + json.dateTime); } ); }); function OnSuccess(responseData) { $("#data").html(responseData.city); } function OnError(XMLHttpRequest, textStatus, errorThrown) { targetDiv = $("#data"); if (errorThrown || textStatus == "error" || textStatus == "parsererror" || textStatus == "notmodified") { targetDiv.replaceWith("請求數據時發生錯誤!"); return; } if (textStatus == "timeout") { targetDiv.replaceWith("請求數據超時!"); return; } } // --></mce:script> </head> <body> <div id="data"></div> </body> </html>
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的利用JQuery jsonp实现Ajax跨域请求 .Net 的*.handler 和 WebService,返回json数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 任天堂发布预热视频,Switch 游戏兑
- 下一篇: asp.net 中ashx、axd的区别