使用ajax post方法选择2
我正在尝试使用ajax加载 这是我的密码:使用ajax post方法选择2,ajax,jquery,jquery-select2,Ajax,Jquery,Jquery 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
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;
}
[WebMethod]
公共静态列表GetFinSys(字符串术语)
{
字符串stringToCompareTo=term.ToLower();
列表结果=新列表();
//财务系统
使用(mapEntities db=new mapEntities())
{
列出finSysCodes=(从db.MPO\u FINSYS\u AMT中的x开始)
选择x).ToList();
foreach(MPO\u FINSYS\u finSysCodes中的金额项目)
{
string valKey=string.Format(“{0}.{1}.{2}”,item.FY,item.MDOT\u MPO\u CD,item.FIN\u SYS);
LookupCodeItem x=新的LookupCodeItem();
x、 Value=valKey;
x、 ShortDescription=string.Format(“{0}.{1}.{2}”,item.FY,item.MDOT\u MPO\u CD,item.FIN\u SYS);
x、 LongDescription=string.Empty;
结果:添加(x);
}
}
返回结果;
}
在文本框中输入数据时,会发出POST请求,并且json的格式似乎正确
但是,来自pagemethod的响应是整个html页面。我的理解是,如果在ajax调用中没有正确设置“contentType”,post方法可能会出现这种情况。我将其设置为与在页面上工作的所有其他ajax调用相同(它们不使用select2)
select2是否忽略“contentType”属性?还是我做了什么错事
**编辑**
发布后,我在select2的github网站上发现了这个问题:
它似乎没有传递contentType。我是否能够绕过selet2内置的ajax帮助程序,使用我自己手动定义的帮助程序?我建议使用WebApi或ServiceStack代替[webmethod]进行数据调用。我也遇到了同样的问题,下面的解决方案适合我:
ajax: {
...
params: { // extra parameters that will be passed to ajax
contentType: "application/json; charset=utf-8",
}
...
}
不要忘记将CSRF令牌添加到post请求中。可能您在客户端做的一切都是正确的,但是服务器拒绝了请求,因为它缺少令牌。例如,请参见PHP Laravel框架:了解更多信息。这是一个建议,应该放在评论中,而不是在回答中。另外,改变编程技术对OP有什么帮助,真的吗?我只是想用一种简单的建议/支持的方法来修复海报。鉴于这是7个月前的事,我现在对此无能为力了!:-)