使用来自asp WebMethod的数据填充jquery自动完成

时间:2015-09-28 10:31:00

标签: javascript jquery jquery-ui jquery-ui-autocomplete

我的asp.net页面中有一个WebMethod,它返回一个字符串,该字符串表示包含我想用作jquery-ui自动完成文本框源的数据的JSON数组。

[WebMethod]
public static string GetCities(string cityName)
{
    JArray json = new JArray(
        new JObject(new JProperty("label", "label1"), new JProperty("category", "cat1"), new JProperty("value", "v1")),
        new JObject(new JProperty("label", "label2"), new JProperty("category", "cat1"), new JProperty("value", "v2")),
        new JObject(new JProperty("label", "label3"), new JProperty("category", "cat2"), new JProperty("value", "v3")),
        new JObject(new JProperty("label", "label4"), new JProperty("category", "cat3"), new JProperty("value", "v4")));
    return json.ToString();
}

javascript代码:

<script type="text/javascript">
    $(function () {
        $("#txtCity").autocomplete({
            source: function (request, response) {
                var param = { cityName: $('#txtCity').val() };
                $.ajax({
                    url: "WebForm1.aspx/GetCities",
                    data: JSON.stringify(param),
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) { return data; },
                    success: function (data) {
                        response(data.d); //here data.d contains the json array string
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                });
            },
            select: function( event, ui ) {
                $( "#output" ).val( ui.item.value );
                return false;
            },
            minLength: 2//minLength as 2, it means when ever user enter 2 character in TextBox the AutoComplete method will fire and get its source data. 
        });
    });
</script>

但我的自动填充会为JSON字符串中的每个字符生成一个项目。我假设我没有正确归还。

1 个答案:

答案 0 :(得分:0)

想出来,

success: function (data) {
                        response($.parseJSON(data.d))
                    },

必须解析JSON。