我有一个ajax脚本,我有点理解它,但仍然需要一些额外的帮助。
$('.images').click(function(){
var imageId = $(this).attr('id');
alert(imageName);
$.ajax({
type: "get",
url: "imageData.php",
dataType: "json",
data: {getImageId: imageId},
error: function() {
alert("error");
},
success: function(data){
alert(imageId);
$("#images_"+imageId).html(data);
}
});
//$('#images_'+imageId).toggle();
});我有这段代码,它放在这个imageData.php文件中
<?php
if(isset($_GET)){
$images = "";
$path = 'img/';
$imageId = $_GET['getImageId'];
$sql = mysql_query("SELECT * FROM images WHERE iID = '".$imageId."'");
while($row = mysql_fetch_array($sql)){
$images .= $path.$row['images'];
}
$json = json_encode($images);
?>
<img src='<?php echo $json;?>'/>
<?php
}
?>为什么当我尝试从$images回显一个字符串时,它会输出错误,但当我执行echo $imageId;时,它会正确输出?我试图从mysql输出一些东西,但不是只输出id。
需要帮助,谢谢!
发布于 2011-05-03 07:27:16
您不需要在这里使用json_encode,因为没有数据需要是JSON格式的。如果查询只返回一个图像,那么也没有理由遍历结果集。
试试这个:
<?php
if(isset($_GET['getImageId'])) {
$path = '';
$imageId = mysql_real_escape_string($_GET['getImageId']); // SQL injection!
$result = mysql_query("SELECT images FROM images WHERE iID = '".$imageId."'");
$row = mysql_fetch_array($result);
if($row) {
$path = 'img/' . $row['images'];
}
}
?>
<?php if($path): ?>
<img src='<?php echo $path;?>'/>
<?php endif; ?>如果iID实际上是一个整数,则需要在查询中省略单引号。
您还必须将dataType从json更改为html,因为您返回的是图像标记()而不是JSON
$.ajax({
type: "get",
url: "imageData.php",
dataType: "html",
data: {getImageId: imageId},
error: function() {
alert("error");
},
success: function(data){
$("#images_"+imageId).html(data);
}
});另一种选择是只返回文本(链接),并在客户端创建图像:
<?php
if(isset($_GET['getImageId'])) {
$path = '';
$imageId = mysql_real_escape_string($_GET['getImageId']); // SQL injection!
$result = mysql_query("SELECT images FROM images WHERE iID = '".$imageId."'");
$row = mysql_fetch_array($result);
if($row) {
echo 'img/' . $row['images'];
}
}
?>在JavaScript中:
$.ajax({
type: "get",
url: "imageData.php",
dataType: "text",
data: {getImageId: imageId},
error: function() {
alert("error");
},
success: function(data){
$("#images_"+imageId).html('<img src="' + data + '" />');
}
});发布于 2011-05-03 07:18:17
由于使用while循环,您可能会得到许多图像,因此您可能希望这样做:
在php中:
$x = 0;
$another = array();
while($row = mysql_fetch_array($sql)){
$another[$x] = $path.$row['images'];
$x++;
}
echo json_encode($another);在jquery中(在你的成功回调中):
$.each(data, function(i, v){
// Do the image inserting to the DOM here v is the path to image
$('#somelement').append('<img src="'+v+'"');
});发布于 2011-05-03 07:20:46
为了输出图像,您必须设置图像标记的src属性(如果已经有的话),或者可以动态创建它。查看此处如何做到这一点> jQuery document.createElement equivalent?
https://stackoverflow.com/questions/5863100
复制相似问题