2014-09-11 26 views
0

無論我如何以List或JSON字符串的形式返回數據,jQuery自動完成插件都不會顯示下拉列表中的值。源代碼指向.aspx的JQuery自動完成

的Javascript:

$("#myText").autocomplete({ 
    source: function (request, response) { 
     $.ajax({ 
      type: "POST", 
      url: "Default.aspx/GetList", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      data: "{'term':'" + request.term + "'}", 
      success: function (data) { 
       response(data); 
      }, 
      error: function (xhr, error) { 
       console.debug(xhr); console.debug(error); 
      } 
     }); 
    }, 
    minLength: 0, 
    select: function (event, ui) { 
     var result = ui.item.id; 
    } 
}); 

服務器端(的.aspx):

[ScriptMethod(ResponseFormat = ResponseFormat.Json), WebMethod] 
public static string GetList(string term) 
{ 
    List<string> list = new List<string>(); 
    list.Add("apple"); 
    list.Add("apricot"); 
    list.Add("apple cider"); 

    string json = "[" + string.Join(",", 
    list.Select(i => 
     "{ 'id': '" + i + "'" + "}" 
    )) + "]"; 

    return json; 
} 

我附上兩張照片,第一顯示了它是如何顯示在瀏覽器,第二個是一個斷點在JavaScript中。

我在做什麼錯?

enter image description here enter image description here

回答

0

使用JavaScriptSerializer,和它的工作。

[ScriptMethod(ResponseFormat = ResponseFormat.Json), WebMethod] 
public static string GetList(string term) 
{ 
    List<string> list = new List<string>(); 
    list.Add("apple"); 
    list.Add("apricot"); 
    list.Add("apple cider"); 

    JavaScriptSerializer serialize = new JavaScriptSerializer(); 
    string result = serialize.Serialize(list); 
    return result; 
}