码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2015-11-30 17:35:17      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

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> 

 

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

标签:

原文地址:http://www.cnblogs.com/kennyliu/p/5007684.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!