How to handle JSON coming from PHP with Javascript

Asked

Viewed 338 times

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, It shows nothing

  • 1

    Try: for(var i=0; i<arr.product.length; i++)...

  • 1

    And instead of "display", use "Description", which is what you have in JSON.

  • Ok @bfavaretto solved! the secret was really put arr.product[i].descricao and não arr[i].descricao. Thank you very much.

1 answer

3

I made a change to your code, just the function myFunction() because in your JSON the array is inside produtos and that’s what you have to iterate on 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;
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.