JQuery - Iterating JSON Response

前端 未结 3 589
温柔的废话
温柔的废话 2021-01-25 16:38

The Story So far....

Trying to learn JS and JQuery and i thought i would start with the basics and try alittle AJAX \"search as you type\" magi

相关标签:
3条回答
  • 2021-01-25 16:50

    Your code:

    $.each(JSONData, function(i, item) {
        var li = $('<li>').append(i).appendTo('ul#live-list');
    });
    

    Says "iterate over the keys and values of the outer JSON structure, and print the keys". The first key is "AccountNumber", so you end up printing that.

    What you want to do is iterate over the array stored at JSONData.AccountNumber, and print the values:

    $.each(JSONData.AccountNumber, function() {
        var li = $('<li>').append(this).appendTo('ul#live-list');
    });
    
    0 讨论(0)
  • 2021-01-25 16:53

    What you probably want is this:

        $.each(JSONData.AccountNumber, function(i, item) {
            var li = $('<li>').append(item).appendTo('ul#live-list');
        });
    
    0 讨论(0)
  • 2021-01-25 17:06

    First, I think keydown is probably the wrong time to do the json call, or at least... it's wrong to do a json call with every keydown. That's too many calls. If I type "hello" in the input box, within about .8 seconds, then there are 5 json requests and responses.

    But you could make it so that it retrieves the json only the first time through, using a flag.

    Something like this:

    $(document).ready(function() {
        var $input = $("#livesearchinput"), filled = false;
        $.ajaxSetup({ cache: false });
        $input.keydown(function(key) {
            if (!filled) {
              filled = true;
              $.getJSON("json101.js", function(JSONData) {
                var $ul =
                $('<ul>')
                    .attr({id: "live-list"})
                    .appendTo('div#livesearchesults');
                $.each(JSONData, function(i, item) {
                    $.each(item, function(j, val) {
                      $('<li>').append(val).appendTo($ul);
                    });
                });
              });
            }
        });
    });
    

    The key thing there is I've used an inner $.each().

    The outer $.each() is probably unnecessary. The JSON you receive has exactly one element in the object - "AccountNumber", which is an array. So you don't need to iterate over all the items in the object.

    That might look like this:

                $.each(JSONData.AccountNumber, function(i, item) {
                    $('<li>').append(item).appendTo($ul);
                });
    
    0 讨论(0)
提交回复
热议问题