2
I have the following json coming from the server:
{"product":[{"descricao":"Xis Bacon","valor":"5.50","codigo":"1551","image":"http:\/\/www.lshtm.ac.uk\/its\/remote\/desktop\/icon___windows.png"},{"descricao":"Coca-cola 2litros","valor":"4.50","codigo":"1551","image":"http:\/\/4.bp.blogspot.com\/_e3P2lU0MP5w\/TA8XYcJ1Y3I\/AAAAAAAABKE\/WP6x-MTBk_M\/s1600\/Logo-icon.png%22"}],"success":1}
How do I display it in my HTML with Javascript?
I’m using:
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://appoficina.atwebpages.com/garcon/listar.php?codigo=1551";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].image + '">' +
arr[i].descricao + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
But nothing happens.
Well, your code seems to be creating a line list based on the received json. What do you want it to do?
– bfavaretto
@bfavaretto, It shows nothing
– Emerson Barcellos
Try:
for(var i=0; i<arr.product.length; i++)...
– bfavaretto
And instead of "display", use "Description", which is what you have in JSON.
– bfavaretto
Ok @bfavaretto solved! the secret was really put
arr.product[i].descricao
andnão arr[i].descricao
. Thank you very much.– Emerson Barcellos