我有一个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。
需要帮助请帮忙,谢谢
这里不需要使用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
,因为您返回的是图像标签(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 + '" />');
}
});
由于使用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+'"');
});
要输出图像,您必须设置图像标记的src
属性(如果您已经有一个),或者您可以动态创建它。查看这里如何做> jQuery文档。createElement等价?