Ajax請求,跨域小坑


今天在上班的時候,被坐在旁邊項目經理叫過去問了一個Ajax請求跨域的問題,一開始沒理解清楚也還有對這個沒有理解的透,后面被打擊的要死。

當時的需求是需要測試一個已發布的api接口,需要在本地寫測試程序去測試接口。

當時的看到代碼大概是這個樣子

$(document).ready(function () {
var args = {
method: "Post",
url: "Test",
data: ({ "id": "FB850EE4-48EE-4502-BFE2-736B02899224" })
// url: "http://xxxxxx/xxxx/api/agency/GetOne",
};
$.ajax(args).done(function (data) {

});
});

當時我犯的第一個錯誤,沒有理解跨域JSONP的概念

JSONP使用只能在GET方式下才能生效,dataType修改成post在Jquery也會轉成GET方式,然而這個接口不支持GET方式請求。

  var args = {
            method: "POST",
            //  url: "Test",
            dataType: 'JSONP',
            data: ({ "id": "FB850EE4-48EE-4502-BFE2-736B02899224" }),
            url: "http://xxxxxxx/xxxx/api/agency/GetOne",
        };
        $.ajax(args).done(function (data) {
        });

 

 

 

所以就在后面看到了類似於這樣的代碼,修改成用WebClient服務器發送POST請求跨域請求的問題。

  public ActionResult Test(string id)
        {
            var url = "http://xxxxxxx/xxxx/api/agency/GetOne";
            System.Net.WebClient wCient = new System.Net.WebClient();
            wCient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            byte[] postData = System.Text.Encoding.ASCII.GetBytes("id="+ id);
            byte[] responseData = wCient.UploadData(url, "POST", postData);
            string returnStr = System.Text.Encoding.UTF8.GetString(responseData);//返回接受的數據 
            return Json(new {  rows = returnStr }, JsonRequestBehavior.AllowGet);
        }

關於AJAX相關的例子已經很多了,在這里附上一個簡單封裝過得例子

base類

var base = {
    /**
     * 遮罩層加載
     * @returns {} 
     */
    ajaxLoading: function() {
        $("<div class=\"datagrid-mask\"></div>").css({ display: "block", width: "100%", height: $(window).height() }).appendTo("body");
        $("<div class=\"datagrid-mask-msg\"></div>").html("正在處理,請稍候...").appendTo("body").css({ display: "block", left: ($(document.body).outerWidth(true) - 190) / 2, top: ($(window).height() - 45) / 2 });
    },
    /**
     * 遮罩層關閉
     * @returns {} 
     */
    ajaxLoadEnd: function() {
        $(".datagrid-mask").remove();
        $(".datagrid-mask-msg").remove();
    },
    /**
     * 
     * @param {} args ajax參數
     * @param {} callback 回調函數
     * @param {} isShowLoading 是否需要加載動態圖片
     * @returns {} 
     */
    ajax: function(args, callback, isShowLoading) {
        //采用jquery easyui loading css效果
        if (isShowLoading) {
            base.ajaxLoading();
        }
        args.url = args.url;
        args = $.extend({}, { type: "POST", dataType: "json" }, args);
        $.ajax(args).done(function(data) {
                if (isShowLoading) {
                    base.ajaxLoadEnd();
                }
                if (callback) {
                    callback(data);
                }
            })
            .fail(function() {
                if (isShowLoading) {
                    base.ajaxLoadEnd();
                } else {
                    window.top.topeveryMessage.alert("提示", "操作失敗");
                }
            });
    }
}

css

.datagrid-mask {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    opacity: 0.3;
    filter: alpha(opacity=30);
    display: none;
}

.datagrid-mask-msg {
    position: absolute;
    top: 50%;
    margin-top: -20px;
    padding: 10px 5px 10px 30px;
    width: auto;
    height: 40px;
    border-width: 2px;
    border-style: solid;
    display: none;
}

.datagrid-mask-msg {
    background: #ffffff url('../Img/loading.gif') no-repeat scroll 5px center;
}

.datagrid-mask {
    background: #ccc;
}

.datagrid-mask-msg {
    border-color: #D4D4D4;
}

方法調用

 base.ajax({
            type: "POST",
            url: "",//url
            contentType: "application/json",
            data: JSON.stringify({})
        }, function(row) {
});

總結:沉下心來,不要太浮躁,每天進步一點點是成功的開始!


免責聲明!

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



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