>我正在尝试使用Ajax的Json方法创建一个花哨的图库。脚本分为三个部分
阿贾克斯电话 :
function getimage(id) {
$.ajax({
type: "GET",
dataType: "json",
url: 'getimages.php',
data:'user='+id,
success: function(data){
$.fancybox([data], {
'padding': 0,
'transitionIn': 'none',
'transitionOut': 'none',
'type' : 'image',
'changeFade' : 0,
'topRatio' : 0.2
});
}
});
return false
}
页面获取图像.php :
<?
include 'config.php'; connect(); session_start();
$user_id = trim(strip_tags($_GET['user']));
$query = "SELECT url as href FROM post WHERE user_id = '$user_id' AND type = 'photo'";
$arr = array();
$rs = mysql_query($query);
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
$json_response = json_encode($arr);
echo $json_response;
?>
Json 响应:
[{"href":"1df4fddf370b2e89949bbf5d6e11e037_1381707753.jpg"},{"href":"42a4701b45eb5b17cee7a8fe1beb4c48_1381957761.jpg"}]
长话短说,每张照片都有"onclick"getimage(id),其中"id"是用户ID。所以getimage.php应该搜索所有照片的用户,并使用json方法将这些视为图库。
问题是数据返回未定义的对象(用可爱的"alert(data)"obj,[obj]对其进行了测试)。现在,问题可能是什么?...我很抱歉我的英语不好。
你的数据已经是一个数组,像这样使用它,
....
success: function(data){
console.log(data);// check in console
if(data.length)
{
$.fancybox(data, { // use data in place of [data]
'padding': 0,
'transitionIn': 'none',
'transitionOut': 'none',
'type' : 'image',
'changeFade' : 0,
'topRatio' : 0.2
});
}
}
要调试,请使用console.log(var mixed);
如果数据是 JSON 对象/字符串,请使用 var myObj = eval('(' + data + ')');
获取 JS-对象。