javascript - getJSON not fetching data -


my code below not fetching data data.js page works fine when json data hard coded page.

<head>     <title>test page</title>     <script>     function jsontest() {         var text;         $.getjson("data.js", function(result) {             text = result;         });         var obj = json.parse(text);         document.getelementbyid("content").innerhtml =         obj.name + "<br>" +         obj.street + "<br>" +         obj.phone;     }     </script> </head> <body onload="jsontest();">     <h1>testing page</h1>     <p id="content"></p> </body> 

my data looks this

{"name":"john johnson","street":"oslo west 16","phone":"555 1234567"} 

am making simple nooby mistake?

the first thing notice you're using getjson in sync mode. won't work since it's executed asynchronous. need place logic inside finish handler

function jsontest() {     var text;     $.getjson("data.js", function(result) {         text = result;         var obj = json.parse(text);         document.getelementbyid("content").innerhtml =         obj.name + "<br>" +         obj.street + "<br>" +         obj.phone;               }); } 

in code, time do

var obj = json.parse(text); 

method getjson didn't return yet text contains default value. sends request server , continue method flow without waiting result.

that's handler for: put logic needs executed when request complete.


Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -