2014-09-11 59 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; 
}