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

    }


}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM