C# jquery webservices 跨域调用的问题解决方案

前台代码:

<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>

 $(‘#getString‘).click(function() {
                $.ajax({
                    url: url + "jQueryMobile.asmx/GetProjInfoList?jsoncallback=?", //webservice总返回Json数据的方法
                    type: ‘POST‘,
                    data: {UserId:‘majunfei‘},
                    //contentType: "application/json",
                    dataType: "json",
                    success: function(res) {
                        //alert(res);
                       // var strRet = res.d; //Net3.5
                        alert(res.result);
                        strRet = $.parseJSON(res); //eval("(" + strRet + ")");
                        var b_ok = strRet.success;
                        var strInfo = strRet.info;
                        alert(strInfo);
                        $.each(strRet.rows, function(index, row) {
                            alert(row.proj_code);
                            alert(row.proj_name)
                        });
                        //data = $.parseJSON(‘‘+data+‘‘);//jquery1.4
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        $("div").html(textStatus);
                        $("div").append("<br/>status:" + XMLHttpRequest.status);
                        $("div").append("<br/>readyState:" + XMLHttpRequest.readyState);
                        $("div").append("<br/>responseText:" + XMLHttpRequest.responseText);
                    }
                });
               // var clientUrl = "http://172.20.1.71:8099/jQueryMobile.asmx/GetProjInfoList?jsoncallback=?";
//                $.getJSON(
//                    clientUrl,
//                    { UserId: ‘majunfei‘ },
//                    function(json) {
//                        alert(json.result);
//                        //  $("#data").html("城市:" + json.city + ",时间:" + json.dateTime);
//                    }
//                );
//                        $.ajax({
//                            url: clientUrl,
//                            dataType: "jsonp",
//                            data : {UserId: ‘majunfei‘},
//                            success : OnSuccess,
//                            error : OnError
//                        });  

//                    function OnSuccess(responseData) {
//                        alert(responseData.result);
//                       // $("#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;
//                        }
//                    }  

                //            $.ajax({
                //                type: "get",
                //               // data: "{UserId:‘majunfei‘}",
                //                async: false,
                //                url: "http://172.20.1.71:8099/jQueryMobile.asmx/GetProjInfoList",
                //                dataType: "jsonp",
                //                jsonp: "callback", //传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
                //                jsonpCallback: "flightHandler", //自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
                //                success: function(res) {
                //                    var strRet = res.d; //Net3.5
                //                    //alert(strRet);
                //                    strRet = eval("(" + strRet + ")");
                //                    var b_ok = strRet.success;
                //                    var strInfo = strRet.info;
                //                    alert(strInfo);
                //                    $.each(strRet.rows, function(index, row) {
                //                        alert(row.proj_code);
                //                       alert(row.proj_name)
                //                    });
                //                    //data = $.parseJSON(‘‘+data+‘‘);//jquery1.4
                //                },
                //                error: function() {
                //                    alert(‘fail‘);
                //                }
                //            });

            });

后台代码:

/// <summary>
    ///WebService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    //若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    [System.Web.Script.Services.ScriptService]
    public class WebService : System.Web.Services.WebService
    {

 /// <summary>
        /// 根据当前用户帐户,获取项目信息列表
        /// </summary>
        /// <param name="UserId">当前用户帐户</param>
        /// <returns></returns>
        [WebMethod]
        public void GetProjInfoList(string UserId)
        {
           // string callback = HttpContext.Current.Request["jsoncallback"];
            string callbackMethodName = HttpContext.Current.Request.Params["jsoncallback"] ?? "";
            var m_DicRoot = new Dictionary<string, object>();
            try
            {
                string strSql = "select proj_code,proj_name from FN_PM_UserDefaultProjLimits(‘" + UserId + "‘) where sortNo<>10";
                DataTable dt_projInfo = TmpSqlServer.ExecuteSqlRead(strSql);
                m_DicRoot.Add("success", true);
                m_DicRoot.Add("info", "读取数据成功");
                var list = new List<Dictionary<string, object>>();
                foreach (DataRow dr in dt_projInfo.Rows)
                {
                    var m_dic = new Dictionary<string, object>();
                    m_dic.Add("proj_code", dr["proj_code"].ToString());
                    m_dic.Add("proj_name", dr["proj_name"].ToString());
                    list.Add(m_dic);
                }
                m_DicRoot.Add("rows", list);
            }
            catch (Exception e)
            {
                m_DicRoot.Add("success", false);
                m_DicRoot.Add("info", e.ToString());
            }
            //关于result这词是你自己自定义的属性
            //会作为回调参数的属性供你调用结果 21
            //HttpContext.Current.Response.ContentType = "application/json";
            //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            // HttpContext.Current.Response.Write(callbackMethodName + "({result:‘true‘})");
            HttpContext.Current.Response.Write(callbackMethodName + "({result:‘" + ListToJson(m_DicRoot) + "‘})");
            HttpContext.Current.Response.End();

            //HttpContext.Current.Response.Write( ListToJson(m_DicRoot));
            //return ListToJson(m_DicRoot);
        }

    }

}
时间: 2024-08-25 01:41:47

C# jquery webservices 跨域调用的问题解决方案的相关文章

Jquery Ajax 跨域调用asmx类型 WebService范例

摘要:Ajax 在 Web 2.0 时代起着非常重要的作用,然而有时因为同源策略(SOP)(俗称:跨域问题(cross domain)) 它的作用会受到限制.在本文中,将学习如何克服合作限制.本文以asmx方式搭建webservice作为测试用后端,给出完整的前后端调用解决方案.范例代码. 关键词: jquery ajax 跨域  webservice  asmx  cross-domain 0 问题分析 0.1 什么是跨域问题? 越来越多的网站需要相互协作.例如,在线房屋租赁网站需要谷歌地图的

Jquery的跨域调用

JQuery1.2后getJSON方法支持跨域读取json数据,原理是利用一个叫做jsonp的概念.当然,究其本质还是通过script标签动态加载js,似乎这是实现真正跨域的唯一方法. getJSON的用法JQuery手册已经写得很详细,参考手册就可以了,很简单.需要指出的一点是getJSON利用的jsonp需要客户端与服务端作出配合. 客户端传递的URL里要包含callback变量,以形如callback=?的形式结尾.(jquery会随机生成一个字符串替换?传递给服务端) 服务端获取客户端传

jquery中的jsonp跨域调用

                                                jquery jsonp跨域调用接口 原文地址:https://www.cnblogs.com/mahmud/p/10131599.html

jQuery跨域调用WebService

jQuery跨域调用WebService举例html: <!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 runat=&quo

jquery ajax jsonp跨域调用实例代码

今天研究了AJAX使用JSONP进行跨域调用的方法,发现使用GET方式和POST方式都可以进行跨域调用,这里简单分享下,方便需要的朋友 客户端代码 复制代码 代码如下: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.WebForm1" %><!DOCTYPE html P

jquery跨域调用wcf

使用jquery跨域调用wcf服务的时候会报如下错误 1 $.ajax({ 2 url: 'http://localhost:28207/Service1.svc/GetData', 3 method: 'get', 4 dataType: 'json', 5 data: { value: val }, 6 success: function (data) { 7 $("label").text("success: " + data); 8 }, 9 error:

实现jquery.ajax及原生的XMLHttpRequest跨域调用WCF服务的方法

关于ajax跨域调用WCF服务的方法很多,经过我反复的代码测试,认为如下方法是最为简便的,当然也不能说别人的方法是错误的,下面就来上代码,WCF服务定义还是延用上次的,如: namespace WcfService1 { [ServiceContract] public interface IAddService { [OperationContract] [WebInvoke(Method="GET",RequestFormat=WebMessageFormat.Json, Resp

使用jsonp跨域调用百度js实现搜索框智能提示,并实现鼠标和键盘对弹出框里候选词的操作【附源码和在线测试地址】

项目中常常用到搜索,特别是导航类的网站.自己做关键字搜索不太现实,直接调用百度的是最好的选择.使用jQuery.ajax的jsonp方法可以异域调用到百度的js并拿到返回值,当然$.getScript也可以实现跨域调用js. jsonp快速入门: [原创]说说JSON和JSONP,也许你会豁然开朗,含jQuery用例 关于jquery.ajax的jsonp方法是用以及其error回调函数不能正确执行,请参考园长dudu的文章: jquery ajax中使用jsonp的限制 jQuery插件jQu

跨域调用webapi

web端跨域调用webapi 在做Web开发中,常常会遇到跨域的问题,到目前为止,已经有非常多的跨域解决方案. 通过自己的研究以及在网上看了一些大神的博客,写了一个Demo 首先新建一个webapi的程序,如下图所示: 由于微软已经给我们搭建好了webapi的环境,所以我们不必去添加引用一些dll,直接开始写代码吧. 因为这只是做一个简单的Demo,并没有连接数据库. 第一步我们要在Models文件夹里添加一个实体类Employees,用来存放数据. Employees.cs里的内容如下: 1