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

Asked

Viewed 569 times

3

I’m making an autocomplete, via AJAX, that enters the web service, "Search in the Database" and returns me a String in the format JSON.

I have to transform the JSON below in a list to iterate on it.

In the data.d get the following String:

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

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

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
    });
});
  • Make an Alert in Success function to see the result.

  • 1

    It must be reading a String, not a JSON, so try to do this: var jsonObj = JSON.parse(data.d);&#xA;$.map(jsonObj, function (item) {.......

  • @Rogerio Alencar Filho posts his comment as an answer, so I can mark it as correct. Another way to do instead of using Json.parse(date. d) would be var data = Eval(data. d)

  • @Rogerioalencarfilho post your answer here please, for me mark it as correct.

1 answer

6


Use JSON.parse(data.d) to turn your JSON into a list of objects and interact over it with the function $.map. The sucess 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 the friend @Rogerioalencarfilho left her in the comments and I found it interesting to leave her here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.