javascript - How do I show an external JS function (returns array) into a html list -
i developing mobile application. need show array in list on html. have function in external .js
file returns array json data retrieved.
this function in javascript:
function getnames() { var url = api + "/name"; $.getjson(url).done(function (answer) { if (!answer.length) { console.warn("empty list"); } api.name = response; (i = 0; < response.length; i++) { $('#names').html(api.name[i].name); } }).fail(function (data, status, error) { console.error("something went wrong"); }); }
this html list want them displayed in:
<div> <div class="widget-container"> <div class="list-group"> <a> <h4 id="names"> <script type="text/javascript"> window.onload = function () { getnames(); }; </script> </h4> </a> repeated 4 times.i have 4 headings meaning need 4 names array returns </div> </div> </div>
the list display them in menu panel. code have shows me last name reason.
if understand correctly, want generate h4
tag each of array elements.
some issues in code:
- there no use in putting
script
tag @ place want inject data. place before closing</body>
tag or else in<head>
tag; - don't use
window.load
. there specific cases useful, not in case. instead usedomcontentloaded
event, or, use jquery, equivalent.ready()
method; - you name json response argument
answer
, start referringresponse
: should stick same variable name; - you assign multiple times html same element
#names
, overwrite previous value , left last value only; - you use
html
method argument pure text. not advised, can problems text contains<
or&
characters, have special meaning in html. instead should use.text()
; - you use
api
variable in strange ways. first seems string (inurl = api + "/name"
), , later assignname
property. although can work, makes code obscure. if object, first statement equalurl = api.tostring() + "/name"
; - the code never adds
h4
element, seems want. happen generate necessaryh4
elements dynamically.
here code adapted accordingly, makes use of fake json provider:
var api = 'https://jsonplaceholder.typicode.com'; function getnames() { var url = api + "/posts"; // change "/name" $.getjson(url).done(function (response) { if (!response.length) { console.warn("empty list"); } $.map(response, function(item) { $('.list-group').append($('<h4>').text(item.title)); // change item.name }); }).fail(function (data, status, error) { console.error("something went wrong"); }); } $(function() { getnames(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <div> <div class="widget-container"> <div class="list-group"> </div> </div> </div>
Comments
Post a Comment