我正在使用当前代码显示图像,具体取决于下拉框中的选择,但我使用的是go按钮。我只想从下拉框中选择显示图像。任何帮助将不胜感激
<form name="product" method="post" action="">
<table align="right" width="10%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Category</td>
<td>
<select name="idnum">
<?php
$sql = "SELECT ID,idnum,title,brief FROM table where passw='tsmith';";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
?>
<option value="<?= $row['idnum']; ?>"><?= $row['title']; ?></option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td> </td>
<td><input name="go" type="submit" value="Go" /></td>
</tr>
</table>
</form>
<div align="center">
<ul class='display'>
<?php
$idnum = (int)$_POST['idnum'];
$sql_search = "SELECT * FROM table WHERE idnum = $idnum";
$search = mysql_query($sql_search);
if (isset($_POST['go'])) {
while ($row = mysql_fetch_assoc($search)) {
$imagepath1= "p".$idnum."n1.jpg";
$path='/components/com/photos/'.$imagepath1;
$image1 =("<img src='$path' width='200' height = '221'/>");
echo $image1;
?>
<img src = "/components/com/photos/p.$row['idnum'].n.jpg">;
<li><a href="<?= $row['title']; ?>"><img src="<?= $row['title']; ?>" border="0"></a></li>
<?php
}
}
else {
}
?>
</div>
答案 0 :(得分:0)
作为如何执行此操作的示例,无需每次都重新加载页面,以下内容可能会有用。 javascript函数附加(内联)到实际的select元素而不是按钮,并在onchange
事件上调用。所选元素的值在ajax函数中使用,并通过POST
请求发送到处理请求的脚本部分,并进行数据库查找以查找图像。您将需要修改该部分代码以返回正确的图像...响应由ajax回调函数处理。
但请注意,现在不鼓励使用mysql_*
函数由于存在SQL注入的风险,所以在深入了解之前,您可能希望考虑学习有关mysqli或PDO的地方。使用准备好的声明来帮助减轻这种风险。你的原始代码和我的代码将POST变量嵌入到了很糟糕的sql中......这只是例如&#39; - )
<?php
/*
include whatever files needed & set session vars if required
*/
if( $_SERVER['REQUEST_METHOD']=='POST' ){
$idnum=$_POST['idnum'];
$sql="select * from `table` where `idnum`='$idnum';";
/* execute the query and generate the response */
exit("<img src='/components/com/photos/{$imagepath1}' />");
}
?>
<!doctype html>
<html>
<head>
<title>Change image</title>
<script>
function changeimg(v){
http=new XMLHttpRequest();
http.onreadystatechange=function(){
if( http.readyState==4 && http.status==200 )cbchangeimg.call( this, http.response );
};
http.open('POST',document.location.href,true);
http.setRequestHeader('Content-type','application/x-www-form-urlencoded');
http.send('idnum='+v);
}
function cbchangeimg(r){
/* process response: change the image */
document.getElementById('myImg').src=r;
}
</script>
</head>
<body>
<img id='myImg' src='/images/placeholder.jpg' />
<select name='idnum' onchange='changeimg(this.value)'>
<option value=1>One
<option value=2>Two
</select>
</body>
</html>