How to handle the JSON coming from PHP with JavaScript [closed]

2

I have the following json who comes 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.

    
asked by anonymous 31.10.2014 / 01:30

1 answer

3

I made a change in your code, only in the myFunction() function because in your JSON the array is inside produtos and this is what you have to iterate in for loop:

function myFunction(arr) {
        var out = "";
        // adicionei a variavel products
        // e atribui a ela os produtos
        var produts = arr.product;

        for(var i = 0; i < produts.length; i++) {
          out += '<a href="' + produts[i].image + '">' + produts[i].descricao + '</a><br>';
        }
        document.getElementById("id01").innerHTML = out;
    }
    
31.10.2014 / 03:13