我确实希望使用Ajax发送HTTP请求,并在用户单击链接时接收响应(来自数据库的图片链接)。我在Ajax函数调用中输入的参数是单击链接的类的值,我通过PHP中的循环获取该类。我认为这有点令人困惑..这是我的代码
Ajax函数调用: index.php
<script>
var current = 0;
function showPics(str) {
if (str=="") {
document.getElementById("displayPic").innerHTML="";
return;
}
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("displayPic").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getpics.php?q="+str,true);
xmlhttp.send();
}
</script>
getpics.php
<?php
$q = $_GET["q"];
$host = "127.0.0.1";
$db = "pcqsp";
$user = "root";
$pass = "";
try {
$conn = new PDO("mysql:host=$host; dbname=$db", $user, $pass);
} catch(Exception $e) {
die('Erreur : ' . $e->getMessage());
}
$req = $conn->prepare('SELECT * FROM screenshot WHERE id_work = :id_work');
$req->execute(array('id_work' => $q));
while ($data = $req->fetch())
{
echo "<img class='popup_pics' src='" . $data['link_screenshot'] . "' />";
}
$req->closeCursor();
?>
对 index.php
的Ajax调用
<?php
// Open a database connection
$host = "127.0.0.1";
$db = "pcqsp";
$user = "root";
$pass = "";
try {
$conn = new PDO("mysql:host=$host; dbname=$db", $user, $pass);
} catch(Exception $e) {
die('Erreur : ' . $e->getMessage());
}
$req = $conn -> query('SELECT * FROM work');
$i = 1;
while ($data = $req -> fetch()) { ?>
<div class="image-even">
<img src="<?php echo $data['cover_work'] ?>" width="421" height="590" />
</div>
<div class="more">
// Here's the problem
<a class="<?php echo $i ?>-popup" href="#displayPics">More details</a>
</div>
<?php
$i ++;
}
?>
<script type="text/javascript">
$current = 0;
$('a[class*="popup"]').click(function(){
current = $(this).attr('class').charAt(0);
showPics(current); //Ajax function call
});
</script>
当我没有通过PHP进行循环时(我正在静态地写作:1-popup
,2-popup
等等。一切正常。
请问你有解决这个问题的方法吗?谢谢。
答案 0 :(得分:0)
你的jquery调用不是在window.ready
事件中构建的。尝试通过执行以下操作将其包含在window.ready
事件中。
<script type="text/javascript">
$current = 0;
$(document).ready(function (e) {
$('a[class*="popup"]').click(function(){
current = $(this).attr('class').charAt(0);
showPics(current); //Ajax function call
});
});
</script>
你的javascript可能在dom准备好之前执行