Retrieving JSON in jquery from a php script
I have this php script which when run outputs this. I cannot seem to fathom out how to access this in jquery I have tried varous methods from tutorials but no avail.
{"name":"photo1.jpg","id":"1"}{"na开发者_C百科me":"photo2.jpg","id":"2"}
{"name":"photo3.jpg","id":"3"}{"name":"photo4.jpg","id":"4"}
<?php
mysql_select_db('news') or die(mysql_error());
//echo "Connected to Database";<?php
$result = mysql_query("SELECT * FROM photos")
or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_assoc( $result )) {
echo json_encode($row);
}
?>
Jquery
$(document).ready(function() {
$.getJSON('photo_get.php', function(data){
alert("Data" + data.name);
});
});
This outputs nothing.
Thanks for any help.
This is not valid JSON:
{"name":"photo1.jpg","id":"1"}{"name":"photo2.jpg","id":"2"}
It should look like this:
[{"name":"photo1.jpg","id":"1"},{"name":"photo2.jpg","id":"2"}]
What you should do is to push every row to some array and then serialize the entire array to JSON.
Eg. use something like this in the loop:
$array[] = $row;
and then serialize the whole thing outside of the loop:
echo json_encode($array);
i think it should be
<?php
$rows=array();
mysql_select_db('news') or die(mysql_error());
//echo "Connected to Database";<?php
$result = mysql_query("SELECT * FROM photos")
or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_assoc( $result )) {
$rows[]=$row;
}
echo json_encode($rows);
?>
$(document).ready(function() {
$.getJSON('photo_get.php', function(data){
$.each(data, function(key, val) {
alert("Data" + val.name);
});
});
});
as its an array
you can push your response to array:
ArrayData = [];
ArrayData = data;
and then loop it:
for (var i; i < ArrayData.length; i++) {
alert(ArrayData[i]['name'])
}
精彩评论