简体   繁体   中英

Displaying JSON data from an ajax call onto HTML

I am working on a project and have everything almost figured out. I am attempting to get a an array of items displayed up on a web page from an ajax call. The code that I currently have is the following:

JQuery Code:

    var submit_form = function(w) {
     $.getJSON($SCRIPT_ROOT + '/death_numbers', {
        number: $('input[name="number"]').val(),
     }, function(data){
        $.each(data, function() {
            alert(data.wars_found);
             $('#war_result').text(data.wars_found);
        });
    });
    return false;
};

 $('a#calculate_two').bind('click', submit_form);

});

Now the line: alert(data.wars_found); will alert me everything that I want. If I do alert(data.wars_found[3]); It will give me the value that I want. So, I know that I have the data correct. The problem is how do I display this data up on the web page. Here is my HTML Code:

<form>
  <input name='number' type='text'/>
  <span id="war_result">?</span>
</form>
<a href=# id="calculate_two">calculate server side</a>

If I do $('#war_result').text(data.wars_found[2]);

It will display one war. However, I want all wars listed on the page. I have spent a few hours looking at posts about the subject and I thought that using $.each would solve the problem. I even tried the following:

     for (i = 0; i < data.wars_found.length; i++){
       $('#war_result').text(data.wars_found[i]);
       console.log(data.wars_found)
     }

That could console log what I wanted but again I want it up on the web page. I believe, at this point that something is wrong with my HTML code. Thank you for any help. Finally, I am working on a Python/Flask project-however, all the data I am pulling is good. Just displaying it as an HTML element is hard!

The simple way with your code:

 var concatenatedData = ''; for (i = 0; i < data.wars_found.length; i++){ concatenatedData += data.wars_found[i]; } $('#war_result').text(concatenatedData); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM