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

本文介绍了一个简单的跨域请求实现方案,包括使用 *.handler 和 WebService 的两种方式,并提供了具体的代码示例。

原文:  http://blog.csdn.net/polarissky/article/details/6429554

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

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


内容概要:本文详细介绍了基于Matlab实现的“梯级水光互补系统最大化可消纳电量期望短期优化调度模型”,属于电力系统领高水平科研成果的复现(EI级别)。该模型聚焦于梯级水电站与光伏发电系统的协同优化调度,通过构建短期优化调度框架,旨在提升可再生能源的电量消纳能力并最大化系统综合效益。研究采用先进的数学优化方法对水光资源进行联合调度,充分考虑了光伏出力的不确定性、水资源约束、系统运行边界条件及电力平衡要求,实现了在多重约束下的电量期望最大化目标。模型不仅具备严谨的理论基础,还具有良好的工程应用前景,适用于新能源高比例渗透背景下电力系统的优化调度研究与实践。; 适合人群:具备电力系统分析、可再生能源利用或优化建模背景的研究生、科研人员及工程技术人员,特别适合致力于复现高水平学术论文(EI/顶刊)研究成果的学习者与开发者。; 使用场景及目标:① 学习并掌握梯级水电与光伏系统协同调度的建模思路与关键技术;② 熟悉基于Matlab的混合整数线性规划(MILP)或其他非线性优化方法在能源系统中的实际应用;③ 提升在新能源消纳、短期调度优化等方向的科研建模能力与代码实现水平,支持二次开发与创新研究。; 阅读建议:建议结合Matlab代码与优化理论同步研读,重点理解目标函数的设计逻辑、各类物理与运行约束的数学表达以及求解器的调用流程,推荐使用YALMIP等建模工具辅助实现,以提高模型构建效率与可读性,便于深入理解与后续拓展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值