我正在使用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