.Net利用JQuery jsonp实现Ajax跨域

2012-01-16 19:58:58|?次阅读|上传:wustguangh【已有?条评论】发表评论

关键词:C#, Web, JQuery|来源:唯设编程网

开发环境: Visual Studio 2005 SP1

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

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=jsonp1326710971952";
        var clientUrl = "http://192.168.120.179:8086/Handler.ashx?jsoncallback=jsonp1326714211254"
        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=jsonp1326714246476";
            var clientUrl = "http://192.168.120.179:8086/WebService.asmx/HelloWorld?jsoncallback=jsonp1326714290151";
            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>

3.结果:

城市:沈阳,时间:2011/5/18 14:49:37
本文转载自:http://blog.csdn.net/polarissky/article/details/6429554
发表评论0条 】
网友评论(共?条评论)..
.Net利用JQuery jsonp实现Ajax跨域