【发布时间】:2013-01-27 16:35:07
【问题描述】:
我正在使用 select2 库来替换选择框。我重新排列了您可以在 Select2 library 页面上找到的示例 7(使用 id 向下滚动
$("#e7").select2 等等...)。我制作了自己的通用处理程序,它返回序列化的 json 数据:
GetData.asxh 视图: 公共类GetData:IHttpHandler { 公共布尔 IsReusable { 得到 { 返回假; } }
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,它应该可以工作,除非您有其他问题。
标签: c# jquery asp.net jsonp generic-handler