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

    }


}

 

posted @ 2014-12-05 16:51  FredTang  Views(3209)  Comments(0Edit  收藏  举报