0

我确实想使用 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>

获取图片.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-popup2-popup等。一切正常。

请问你有这个问题的解决方案吗?谢谢你。

4

1 回答 1

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>

可能在 dom 准备好之前执行了您的 javascript

于 2013-07-18T13:38:37.590 回答