利用JQuery jsonp实现Ajax跨域请求 .Net 的*.handler 和 WebService,返回json数据

开发环境: Visual Studio 2005 SP1

部署环境:Windows Server 2008 r2 + IIS 7

 

1.新建数据源项目CrossDomain

    主要文件如下:

   1.Handler.ashx   作为jquery跨域请求*.handler的响应,代码如下:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Web;  
  4. using System.Web.Services;  
  5. namespace CrossDomain  
  6. {  
  7.     /// <summary>  
  8.     /// $codebehindclassname$ 的摘要说明  
  9.     /// </summary>  
  10.     [WebService(Namespace = "http://tempuri.org/")]  
  11.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  12.     public class Handler : IHttpHandler  
  13.     {  
  14.         public void ProcessRequest(HttpContext context)  
  15.         {  
  16.             context.Response.ContentType = "text/plain";  
  17.             string callbackMethodName = context.Request.Params["jsoncallback"];  
  18.             string currentCity = context.Request["city"];  
  19.             currentCity = string.IsNullOrEmpty(currentCity) ? "北京" : "沈阳";  
  20.             string result = callbackMethodName + "({/"city/":" + "/"" + currentCity + "/", /"dateTime/":" + "/"" + DateTime.Now + "/"});";  
  21.             context.Response.Write(result);  
  22.         }  
  23.         public bool IsReusable  
  24.         {  
  25.             get  
  26.             {  
  27.                 return false;  
  28.             }  
  29.         }  
  30.     }  
  31. }  

2.WebService.asmx   作为jquery跨域请求WebService的响应,代码如下:

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Web;  
  4. using System.Web.Services;  
  5. namespace CrossDomain  
  6. {  
  7.     /// <summary>  
  8.     /// WebService 的摘要说明  
  9.     /// </summary>  
  10.     [WebService(Namespace = "http://tempuri.org/")]  
  11.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  12.     [System.ComponentModel.ToolboxItem(false)]  
  13.     public class WebService : System.Web.Services.WebService  
  14.     {  
  15.         [WebMethod]  
  16.         public void HelloWorld(string city)  
  17.         {  
  18.             string callbackMethodName = HttpContext.Current.Request.Params["jsoncallback"] ?? "";  
  19.             city = string.IsNullOrEmpty(city) ? "北京" : "沈阳";  
  20.             string result = callbackMethodName + "({/"city/":" + "/"" + city + "/", /"dateTime/":" + "/"" + DateTime.Now + "/"});";  
  21.             HttpContext.Current.Response.Write(result);  
  22.             HttpContext.Current.Response.End();  
  23.         }  
  24.         [WebMethod]  
  25.         public void ws(string name, string time)  
  26.         {  
  27.             HttpRequest Request = HttpContext.Current.Request;  
  28.             string callback = Request["callback"];  
  29.             HttpResponse Response = HttpContext.Current.Response;  
  30.             Response.Write(callback + "({msg:'this is" + name + "jsonp'})");  
  31.             Response.End();  
  32.         }  
  33.     }  
  34. }  

 3.Web.config 需要修改web.config文件,注意webServices 节(这是请求webservice获取数据的关键)具体如下:

 

 

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <configuration>  
  3.   
  4.     
  5.     <appSettings/>  
  6.     <connectionStrings/>  
  7.     
  8.     <system.web>  
  9.         <!--   
  10.             设置 compilation debug="true" 可将调试符号插入  
  11.             已编译的页面中。但由于这会   
  12.             影响性能,因此只在开发过程中将此值   
  13.             设置为 true。  
  14.         -->  
  15.         <compilation debug="false">  
  16.         </compilation>  
  17.         <!--  
  18.             通过 <authentication> 节可以配置 ASP.NET 用来   
  19.             识别进入用户的  
  20.             安全身份验证模式。   
  21.         -->  
  22.         <authentication mode="Windows" />  
  23.         <!--  
  24.             如果在执行请求的过程中出现未处理的错误,  
  25.             则通过 <customErrors> 节可以配置相应的处理步骤。具体说来,  
  26.             开发人员通过该节可以配置  
  27.             要显示的 html 错误页  
  28.             以代替错误堆栈跟踪。  
  29.         <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">  
  30.             <error statusCode="403" redirect="NoAccess.htm" />  
  31.             <error statusCode="404" redirect="FileNotFound.htm" />  
  32.         </customErrors>  
  33.         -->  
  34.       <webServices>  
  35.         <protocols>  
  36.           <add name="HttpGet"/>  
  37.           <add name="HttpPost"/>  
  38.         </protocols>  
  39.       </webServices>  
  40.     </system.web>  
  41. </configuration>  

2.新建跨域请求测试项目CrossDomainRequestTest

 1.CrossDomainRequestHandler.htm 跨域请求*.handler获取josn格式数据测试页,代码如下:

 

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml" >  
  3. <head>  
  4.     <title></title>  
  5.         <mce:script type="text/javascript" language="javascript" src="js/jquery-1.4.4.js" mce_src="js/jquery-1.4.4.js"></mce:script>  
  6.     <mce:script type="text/javascript" language="javascript" src="js/jquery-1.4.4.js" mce_src="js/jquery-1.4.4.js"></mce:script>  
  7.     <mce:script type="text/javascript" language="javascript"><!--  
  8.         $(document).ready(function() {  
  9. //        var clientUrl = "http://localhost:4508/Handler.ashx?jsoncallback=?";  
  10.         var clientUrl = "http://192.168.120.179:8086/Handler.ashx?jsoncallback=?"  
  11.         var currentCity = "哈尔滨";  
  12.         $.ajax({  
  13.             url: clientUrl,  
  14.             dataType: "jsonp",  
  15.                 data : {city : currentCity},  
  16.                 success : OnSuccess,  
  17.                 error : OnError  
  18.             });  
  19.         });  
  20.         function OnSuccess(json) {  
  21.             $("#data").html("城市:" + json.city + ",时间:" + json.dateTime);  
  22.         }  
  23.         function OnError(XMLHttpRequest, textStatus, errorThrown) {  
  24.             targetDiv = $("#data");  
  25.             if (errorThrown || textStatus == "error" || textStatus == "parsererror" || textStatus == "notmodified") {  
  26.                 targetDiv.replaceWith("请求数据时发生错误!");  
  27.                 return;  
  28.             }  
  29.             if (textStatus == "timeout") {  
  30.                 targetDiv.replaceWith("请求数据超时!");  
  31.                 return;  
  32.             }  
  33.         }  
  34.       
  35. // --></mce:script>  
  36. </head>  
  37. <body>  
  38. <div id="data"></div>  
  39. </body>  
  40. </html>  
  41. 2.CrossDomainRequestWebService.htm 跨域请求WebService *.asmx 获取josn格式数据测试页,代码如下:
    1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    2. <html xmlns="http://www.w3.org/1999/xhtml" >  
    3. <head>  
    4.     <title></title>  
    5.         <mce:script type="text/javascript" language="javascript" src="js/jquery-1.4.4.js" mce_src="js/jquery-1.4.4.js"></mce:script>  
    6.     <mce:script type="text/javascript" language="javascript"><!--  
    7.         $(document).ready(function() {  
    8. //            var clientUrl = "http://localhost:4508/WebService.asmx/HelloWorld?jsoncallback=?";  
    9.             var clientUrl = "http://192.168.120.179:8086/WebService.asmx/HelloWorld?jsoncallback=?";  
    10.             var currentCity = "哈尔滨";  
    11.             $.getJSON(  
    12.                 clientUrl,  
    13.                 { city: currentCity },  
    14.                 function(json) {  
    15.                     $("#data").html("城市:" + json.city + ",时间:" + json.dateTime);  
    16.                 }  
    17.             );  
    18.         });  
    19.         function OnSuccess(responseData) {  
    20.             $("#data").html(responseData.city);  
    21.         }  
    22.         function OnError(XMLHttpRequest, textStatus, errorThrown) {  
    23.             targetDiv = $("#data");  
    24.             if (errorThrown || textStatus == "error" || textStatus == "parsererror" || textStatus == "notmodified") {  
    25.                 targetDiv.replaceWith("请求数据时发生错误!");  
    26.                 return;  
    27.             }  
    28.             if (textStatus == "timeout") {  
    29.                 targetDiv.replaceWith("请求数据超时!");  
    30.                 return;  
    31.             }  
    32.         }  
    33.       
    34. // --></mce:script>  
    35. </head>  
    36. <body>  
    37. <div id="data"></div>  
    38. </body>  
    39. </html> 
    40.  

输出:城市:沈阳,时间:2011/5/18 14:49:37

posted @ 2012-05-04 11:03  kevin655  阅读(1309)  评论(0编辑  收藏  举报