How to iterate over a JSON file to appear in the Auto Complete listing?

3

I am doing an autocomplete, via AJAX , which enters the Web service, "search in the Bank" and returns me a String in the format JSON .

I have to transform the JSON down into a list to iterate over it.

In data.d I get the following String:

"[{"IDPais":1,"Pais1":"Brasil","IDIdioma":1}]"

When reading the file JSON with the function $.map it gives error in the console.

My code:

$(function() {
    $("#<%=txtPais.ClientID%>").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: '<%=ResolveUrl("../ws/AutoComplete.asmx/GetListaPais")%>',
                data: "{ 'prefixText': '" + request.term + "','contextKey': '" + $("#<%=rblIdiomas.ClientID%> input:checked").val() + "'}",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function(data) {
                    response($.map(data.d, function(item) {
                        return {
                            label: item.Pais1,
                            val: item.IDPais
                        }
                    }))
                },
                error: function(response) {
                    alert(response.responseText);
                },
                failure: function(response) {
                    alert(response.responseText);
                }
            });
        },
        minLength: 1
    });
});
    
asked by anonymous 08.10.2014 / 15:59

1 answer

6

Use JSON.parse(data.d) to transform your JSON into a list of objects and interact with it with the $.map function. The% w / ajax% should look like this:

success: function (data) {
    var dados = JSON.parse(data.d);
    response($.map(dados, function (item) {
        return {
            label: item.Pais1,
            val: item.IDPais
        }
    }));
}

I answered the question because my friend @RogerioAlencarFilho left her in the comments and I found it interesting to leave her here.

    
14.01.2015 / 17:23