即使AJAX调用返回值,也要经过formatAjax Error

时间:2014-10-07 02:55:21

标签: javascript jquery ajax jquery-select2

我在jQuery上有这个代码:

$("#filtro").select2({
    minimumInputLength: 3,
    ajax: {
        url: Routing.generate('searchCompany'),
        dataType: 'jsonp',
        data: function (filter) {
            return {
                q: filter
            };
        },
        results: function (data) {
            return {
                results: data.entities
            }
        }
    },
    formatNoResults: function () {
        console.log("1");
        return "No companies found";
    },
    formatAjaxError: function () {
        console.log("2");
        return "No companies found";
    }
});

服务器端返回这样的JSON,例如:

{
   "entities":[
      {
         "id":1,
         "nombre":"Ad modi ea."
      }
   ]
}

但是在元素中我总是看到“没有找到公司”,而在控制台中输出“2”,我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

尝试

$("#filtro").select2({
    minimumInputLength: 0,
    ajax: {
        url: '/echo/json/',
        //your response type is json not jsonp
        dataType: 'json',
        params: {
            method: 'post'
        },
        data: function () {
            return {
                json: JSON.stringify(json)
            }
        },
        results: function (data) {
            return {
                results: data.entities
            }
        }
    },
    formatNoResults: function () {
        console.log("1");
        return "No companies found";
    },
    formatAjaxError: function () {
        console.log("2");
        return "No companies found";
    },
    //since there is no text property in your json, you need to provide this
    formatResult: formatSelection,
    formatSelection: formatSelection
});

function formatSelection(item) {
    return item.nombre
};

演示:Fiddle