点击链接的Ajax请求,它的类值是由PHP得到的,没有得到任何响应

时间:2013-07-18 12:47:06

标签: php ajax jquery

我确实希望使用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-popup2-popup等等。一切正常。

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

1 个答案:

答案 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准备好之前执行