您的位置:首页 > Web前端 > JQuery

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

2017-06-07 10:09 1551 查看
1.新建数据源项目CrossDomain

    主要文件如下:

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

   

[csharp] view
plain copy

 print?

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的响应,代码如下:

 

[csharp] view
plain copy

 print?

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获取数据的关键)具体如下:

 

[html] view
plain copy

 print?

<?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格式数据测试页,代码如下:

[html] view
plain copy

 print?

<!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格式数据测试页,代码如下:

[html] view
plain copy

 print?

<!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> 
  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: