zoukankan      html  css  js  c++  java
  • 利用JQuery jsonp实现Ajax跨域请求 .Net 的*.handler 和 WebService,返回json数据

    1:跨域请求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;
                }
            }
        }
    }

    前端页面:

    <!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:Webservice作为跨域请求的目标:

    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;
                }
            }
        }
    }

    页面代码:

    <!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>

    注意配置webconfig:

        <webServices>  
            <protocols>  
              <add name="HttpGet"/>  
              <add name="HttpPost"/>  
            </protocols>  
          </webServices> 

    JSONP乱码的解决:

    后台:

               string result = PublicMethod.DataTableToJson(user);
                    result = jsonp(callbackMethodName, result);
                    HttpContext.Current.Response.ContentType = "text/xml; charset=gb2312";
                    HttpContext.Current.Response.Charset = "gb2312";
                    HttpContext.Current.Response.Write(result);
                    HttpContext.Current.Response.End();

    前台:

           var clientUrl = "http://localhost:63526/UKWebService.asmx/GetUserInfoByUKNo?jsoncallback=?";
                $.getJSON(
                clientUrl,
                { UkNo: '201588884485' },
                function (json) {
                    var r = eval(json);
                    alert(r[0].PersonName);
                }
                );
  • 相关阅读:
    移动端支付6位密码框
    移动端canvas刮刮乐
    原生ajax请求json数据
    canvas绘制video
    移动端阻止默认长按选中文本和弹出菜单、点击阴影
    前端移动端相关的代码(pc端与移动端自动切换)
    统一管理网站中的某些需要定期更新的时间届数 倒计时 ( 换届 之类的网站)( 兼容ie )
    Hbuilder 常用快捷键汇总
    文件找不到,路径错误问题
    图片清晰度问题
  • 原文地址:https://www.cnblogs.com/kennyliu/p/5007684.html
Copyright © 2011-2022 走看看