So I have a problem with JSONP. I finally managed to load my JSONP data into my html file, but I can't seem to print all the data. I already tried the for loop and $.each, but no succes.
JSONP in php file
<?php echo $_GET["callback"] ?> (
{
"expo":"pit",
"datum":"05.06.2011 - 05.06.2016",
"img":"images/pit_home.jpg",
"link":"indexpit.html"
},
{
"expo":"Space Odessy 2.0",
"datum":"17.02 - 19.05.2013",
"img":"images/so_home.jpg",
"link":"indexso.html"
}
);
Script for calling the JSONP
<script type="text/javascript">
$.ajax({
type: 'GET',
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
url: 'http://mllsdemode.be/Ex-cache/home.php',
success: function(json) {
for (var key in json) {
var el = document.getElementById("home");
el.innerHTML = "<li><a href=" + json.link + " data-ajax='false'><img src=" + json.img + "><div class='dsc'>" + json.expo + "<br><em>" + json.datum + "</em></div></a></li>";
}
},
error: function() { alert("Error reading jsonP file"); }
});
</script>
Anyone know what I should do to print all the info? At this moment I only get the data for pit, not the data for Space Odessy 2.0.
The JSONP should be:
<?php echo $_GET["callback"] ?> (
[
{
"expo":"pit",
"datum":"05.06.2011 - 05.06.2016",
"img":"images/pit_home.jpg",
"link":"indexpit.html"
},
{
"expo":"Space Odessy 2.0",
"datum":"17.02 - 19.05.2013",
"img":"images/so_home.jpg",
"link":"indexso.html"
}
]
);
You were missing the []
around the array, so you were passing two arguments to the callback function instead of one array.
After that, your loop is wrong. It's processing a single object, not an array, and replacing the home
inner HTML each time instead of appending.
success: function(json) {
var $home = $("#home");
$home.empty();
$.each(json, function(i, el) {
$home.append("<li><a href=" + el.link + " data-ajax='false'><img src=" + el.img + "><div class='dsc'>" + el.expo + "<br><em>" + el.datum + "</em></div></a></li>");
});
}
<?php echo $_GET["callback"] ?> ([
{
"expo":"pit",
"datum":"05.06.2011 - 05.06.2016",
"img":"images/pit_home.jpg",
"link":"indexpit.html"
},
{
"expo":"Space Odessy 2.0",
"datum":"17.02 - 19.05.2013",
"img":"images/so_home.jpg",
"link":"indexso.html"
}]);
.
$(json).each(function (index, item) {
var el = document.getElementById("home");
el.innerHTML += ("<li><a href=" + item.link + " data-ajax='false'><img src=" + item.img + "><div class='dsc'>" + item.expo + "<br><em>" + item.datum + "</em></div></a></li>");
});
Try this.
json = $.parseJSON(json);
now you can loop through it like following :
for(i=0; i<json.length; i++)
{
alert(json[i].expo);
}
Your Array must be in this format [{},{}];
Thanks