jQuery插件select2跨域设置xhrFields参数

ajax跨越时默认不带cookie,如果需要带cookie调用,需要设置参数 xhrFields: { withCredentials: true },如:

$.ajax({url : "http://www.baidu.com",
        dataType : 'json',
        xhrFields: { withCredentials: true },
        success:function(data){console.log(data)}
        })

但是在使用jQuery插件select2跨域时,在ajax下直接设参数 xhrFields: { withCredentials: true } 无效,需要在外面包一层params,如下:

$("#s2_input").select2({
    placeholder: "",
    ajax: {
        url: "http://www.baidu.com",
        params: {
            xhrFields: { withCredentials: true }
        },
        dataType: 'json',
        data: function (term, page) {
            return {
                page: page,
                count: 25,
                q: term
            };
        },
        results: function (data, page) {
            var more = (page * 25) < data.total;
            return { results: data.items, more: more };
        }
    },
    formatResult: namesformat,
    formatSelection: namesformat,
    escapeMarkup: function (m) { return m; },
    initSelection: function (element, callback) {
        var data = [];
        $(element.val().split(",")).each(function () {
            data.push({ id: this, text: this });
        });
        callback(data);
    }
});

 

posted @ 2017-12-19 19:39  svice  阅读(1484)  评论(0编辑  收藏  举报