JQuery Autocomplete,源指向.aspx

时间:2014-09-11 06:26:09

标签: jquery jquery-autocomplete

无论我如何以List或JSON字符串的形式返回数据,jQuery Autocomplete插件都不会在下拉列表中显示这些值。

使用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;
}

我附上了2张图片,第一张是在浏览器中显示的,第二张是javascript中的断点。

我做错了什么?

enter image description here enter image description here

1 个答案:

答案 0 :(得分: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;
}