javascript - How to display all titles from Json file in HTML -
i have function:
function: function getsimilar() { $.ajax({ type: "get", url: "../content/test.txt", datatype: "json", success: function (data) { var similar; var id = parseint(document.getelementbyid('similar').getattribute('data-id')) || 0; if(similar) { document.queryselector('#similar').innerhtml = similar.title; document.getelementbyid('similar').setattribute('data-id', similar.id); } }, error: function (data) { console.error('error in ajax call'); console.error(data); } }); }
and json file article titles:
[{ "id": 0, "title": "first blog", "content": "lorem ipsum dummy has been industry's standard dummy text ever ." }, { "id": 1, "title": "second blog", "content": "industry. lorem ipsum has been industry's standard dummy text ever since ." }, { "id": 2, "title": "third blog", "content": "lorem ipsum dummy text of printing , typesetting industry. lorem ipsum ." }]
i want display titles in 1 of html divs called similar me it? suppose should create list in html. thanks
you need use loop iterate on items received in order form list of items added dom. create bulk of new dom elements prefer collect them in string buffer , add @ once - bit more faster, not necessary. code may this:
javascript
function getsimilar() { $.ajax({ type: "get", url: "../content/test.txt", datatype: "json", success: function (data) { var i, l, list; if(data && data.length > 0) { list = ['<ul>']; for(i=0,l=data.length; i<l; i++) { list.push('<li data-id="' + data[i].id + '">' + data[i].title + '</li>'); } list.push('</ul>'); $('#similar').html(list.join('')); } }, error: function (data) { console.error('error in ajax call'); console.error(data); } }); }
working example: http://plnkr.co/edit/o6ytxo9nnglqs7rsu8pf?p=preview
Comments
Post a Comment