Ajax請求,跨域小坑

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

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

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

$(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的概念ajax

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

  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請求跨域請求的問題。api

  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("提示", "操做失敗");
                }
            });
    }
}

cssapp

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

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

相關文章
相關標籤/搜索