Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    May 2012
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts

    How include json file in html file?

    Hello
    I have json file "mydata.json", in this file is some json-encoded data, i want obtain this data in file "index.html" and process this data in javascript. but a dont know how to connect.json file in .html file?
    Tell me please.

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    You should request this file from the server using Ajax (to some server side script, e.g. PHP) and convert the result to a native Javascript object literal. Something in the lines of
    Code:
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open('GET', 'path/to/script.php', true);
    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState==4) {
            if(xmlhttp.status==200) {
                var myobject = JSON.parse(xmlhttp.responseText);
                // at this point you have a native Javascript object representing the JSON string that you received from the server
                // e.g.
                document.getElementById('destination').innerHTML = myobject.name + "<br/>" + myobject.surname;
            }
        }
    };
    xmlhttp.send(null);
    The server side script should then just read the .json file and output it


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •