Second part of my javascript isn't executing after rendering some JSON
Hey guys I was wondering why my last script in this fi开发者_开发技巧le isn't working - its suppose to take the value that is being pulled from JSON and compare it to a set value. Thanks for all the help everyone!
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var url = "https://graph.facebook.com/tenniswarehouse?callback=?";
$.getJSON(url,function(json){
var html = "<div id=\"tester\">" + json.likes + "</div>";
//A little animation once fetched
$('.facebookfeed').html(html);
});
});
</script>
</head>
<body onload="timeMsg()">
<div class="facebookfeed">
<h2></h2>
</div>
<script type="text/javascript">
var x =document.getElementById("tester").innerHTML;
if (x < 56700) {
document.write("worked")
}
else {
document.write("didn't work")
}
</script>
</body>
</html>
You need this to be in a function, like:
function myFunc() {
var x =document.getElementById("tester").innerHTML;
if (x < 56700) {
document.write("worked")
}
else {
document.write("didn't work")
}
}
And then call it like so:
$.getJSON(url,function(json){
var html = "<div id=\"tester\">" + json.likes + "</div>";
//A little animation once fetched
$('.facebookfeed').html(html);
myFunc();
});
Because you are executing that code before tester is added to the DOM.
Your function in head is executed on page load. However, javascript code in body is executed when the page is rendered (before page load), therefore it is executed prior to AJAX request.
To fix that, you should move the script from body to json handler. like that:
$(function() {
var url = "https://graph.facebook.com/tenniswarehouse?callback=?";
$.getJSON(url,function(json){
var html = "<div id=\"tester\">" + json.likes + "</div>";
//A little animation once fetched
$('.facebookfeed').html(html);
var x =document.getElementById("tester").innerHTML;
if (x < 56700) {
document.write("worked")
} else {
document.write("didn't work")
}
});
});
精彩评论