使用ajax post方法选择select2

Ama*_*son 12 ajax jquery jquery-select2

我正在尝试使用带有ajax加载的select2.

这是我的代码:

clonedTemplate.find('[id^=detailsPhaseFinanceMinor_]').select2({
    placeholder: "Select",
    minimumInputLength: 1,
    ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: "mapBasic.aspx/GetFinSys",
        dataType: 'json',
        data: function (term, page) {
            return "{'term':\"" + term + "\"}";
        },
        results: function (data, page) { // parse the results into the format expected by Select2.
            // since we are using custom formatting functions we do not need to alter remote JSON data
            return { results: data.Value };
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

ajax调用是在同一页面的代码隐藏中的webmethod/pagemethod:

[WebMethod]
    public static List<LookupCodeItem> GetFinSys(string term)
    {
        string stringToCompareTo = term.ToLower();

        List<LookupCodeItem> result = new List<LookupCodeItem>();


        // FIN SYS
        using (mapEntities db = new mapEntities())
        {
            List<MPO_FINSYS_AMT> finSysCodes = (from x in db.MPO_FINSYS_AMT
                                                select x).ToList();

            foreach (MPO_FINSYS_AMT item in finSysCodes)
            {
                string valKey = string.Format("{0}.{1}.{2}", item.FY, item.MDOT_MPO_CD, item.FIN_SYS);
                LookupCodeItem x = new LookupCodeItem();
                x.Value = valKey;
                x.ShortDescription = string.Format("{0}.{1}.{2}", item.FY, item.MDOT_MPO_CD, item.FIN_SYS); ;
                x.LongDescription = string.Empty;
                result.Add(x);

            }
        }

        return result;
    }
Run Code Online (Sandbox Code Playgroud)

将数据输入文本框时,会发出POST请求,并且json发送似乎已正确格式化.

但是,pagemethod的响应是整个html页面.我的理解是,如果您没有在ajax调用中正确设置"contentType",则可以使用post方法.我设置它与我在页面上工作的所有其他ajax调用相同(它们不使用select2).

select2是否忽略"contentType"属性?或者还有其他我做错了吗?

**编辑**发布后,我发现在select2的github网站上列出了这个问题: 问题492 - 向Ajax添加对contentType的支持

它似乎没有通过contentType.我能绕过selet2内置的ajax帮助器并使用我自己手动定义的一个吗?

Way*_*ley -7

我建议使用 WebApi 或 ServiceStack 进行数据调用,而不是 [webmethod]。