使用ajax post方法选择select2

时间:2013-01-18 16:26:42

标签: ajax jquery jquery-select2

我正在尝试使用select2加载ajax。

这是我的代码:

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

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;
    }

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

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

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

**编辑** 发布此内容后,我发现在select2的github网站上列出了此问题: Issue 492 - Add Support for contentType to Ajax

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

3 个答案:

答案 0 :(得分:4)

我有同样的问题,以下解决方案对我有用:

ajax: {
   ...
   params: { // extra parameters that will be passed to ajax
        contentType: "application/json; charset=utf-8",
   }
   ...
}

答案 1 :(得分:1)

不要忘记将CSRF令牌添加到您的帖子请求中。可能是您在客户端执行所有操作,但服务器拒绝该请求,因为它缺少令牌。有关详细信息,请参阅PHP Laravel框架:https://laravel.com/docs/5.4/csrf#csrf-x-csrf-token

答案 2 :(得分:-5)

我建议您使用WebApi或ServiceStack代替[webmethod]进行数据调用。

相关问题