我正在使用select2库来替换选择框。我重新安排了示例7,您可以在Select2 library页面找到(向下滚动ID为 $("#e7").select2
等)。我做了我自己的通用处理器返回序列化JSON数据:jQuery select2与远程数据和asp.net
GetData.asxh观点: 公共类的GetData:IHttpHandler的 { 公共BOOL IsReusable { 得到 { 返回FALSE; }}
public class RecipesList
{
public int total { get; set; }
public List<TopRecipeTable> recipes { get; set; }
public RecipesList() { }
public RecipesList(int total, List<TopRecipeTable> recipes)
{
this.total = total;
this.recipes = recipes;
}
}
private string GenerateJsonSerializedObject(int languageId, string orderBy)
{
RecipesList recipeList = new RecipesList(15, DBDataBase.GetTopRecipesByNumberOfRecipes(languageId, 15));
return new JavaScriptSerializer().Serialize(recipeList);
}
public void ProcessRequest(HttpContext context)
{
int languageId;
bool languageParsed = int.TryParse(context.Request["languageId"], out languageId);
string orderBy = (string)context.Request["orderBy"];
if (languageParsed && orderBy != string.Empty)
{enter code here
context.Response.ContentType = "application/json";
var jsonValue = GenerateJsonSerializedObject(languageId, orderBy);
context.Response.Write(jsonValue);
}
}
这个通用的处理程序返回的JSON正确的格式(我this URL检查它)。我的结果(json)也与上面提到的页面上的例子相同。但是在这个jquery之后不再触发。
我的脚本:
$(document).ready(function() {
$("#e8").select2({
placeholder: "Search for a recipe",
//minimumInputLength: 1,
ajax: {
url: "/Handlers/GetData.ashx",
dataType: 'jsonp',
data: function (term, page) {
return {
languageId: 1,
orderBy: "TA"
};
},
results: function (data, page) {
alert(data.total);
var more = (page * 10) < data.total; // whether or not there are more results available
// notice we return the value of more so Select2 knows if more results can be loaded
return { results: data.recipes, more: more };
}
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection, // omitted for brevity, see the source of this page
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});
});
我试着写在最初的例子同样alert(data.total)
和它的工作,但不是在我的版本。所以我有正确的json格式,jquery调用我的通用处理程序,并且还接收参数languageId ...并且还返回正确的json格式,但没有任何结果。我不知道我是否在这里错过了一些东西,因为我确信这个东西也可以和一个通用处理器一起工作。我希望我提供了足够的有关我的问题的信息。
I can also add my result in jquery .ajax error handler :
xhr.status = 200
ajaxOptions = parsererror
horwnError = SyntaxError : invalid label
If this is any helpful information
您正在序列化JavaScript,它会为您提供json响应。然而在ajax调用中你指定了jsonp的dataType。把它改为json,它应该可以工作,除非你有其他问题。 – DarrellNorton 2014-08-11 00:20:57