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

问题描述:

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

[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字符串的每个字符产生项。我假设我没有正确地返回它。

想通了,

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

不得不解析JSON。