如何构建ajax调用在刷新时随机化网页上的图像?

时间:2017-03-23 03:26:27

标签: javascript php ajax

我正在开展一个小组项目,我希望能够从网页上的数据库中随机化图像,并将这些图像链接到适当的网页。我是ajax和php的总菜鸟,而且我一直专注于本网站的前端开发。到目前为止,我已经获得了这些php方法

function executeZParamQuery($sql) 

{
    //executes and returns data from database
    $stmt = mysqli_stmt_init($mysqli);
    mysqli_stmt_prepare($stmt, $sql);

    if (mysqli_stmt_execute($stmt))
    {
        $result = iimysqli_stmt_get_result($stmt);

        $data = array();
        while ($row = iimysqli_result_fetch_array($result))
            $data[] = $row;

        mysqli_stmt_close($stmt);
        return $data;
     }

    error_log("Failed to execute prepared statement: "
    .mysqli_stmt_error($stmt));
    die ("Failed to execute prepared statement: "
    .mysqli_stmt_error($stmt));
}

function getAllImg()
{
    $sql = "SELECT RecipeID, PictureID FROM Pictures";

    echo json_encode(executeZParamQuery($sql));
} 

但我不知道如何利用ajax实际操作这些函数并生成随机图像。请发送一些指导。

编辑:想我会告诉你们html以及我想要链接图片和链接的地方

<div class="banner">
    <a href="">
    <img class="first" src="http://i.imgur.com/gZo0lXk.jpg" alt=""        style="width:350px; height: 233px;" />
    </a>
  <a href="">
    <img src="http://i.imgur.com/o0H3If2.png" alt="" style="width:350px; height: 233px;" />
  </a>
  <a href="">
    <img src="http://i.imgur.com/p1DFGse.png" alt="" style="width:350px; height: 233px;" />
  </a>
  <a href="">
    <img src="http://i.imgur.com/ck0dtSd.png" alt="" style="width:350px; height: 233px;" />
  </a> 
  <a href="">
    <img src="http://i.imgur.com/RAHLxlm.png" alt="" style="width:350px; height: 233px;" />
  </a>
  <a href="">
    <img src="http://i.imgur.com/bVGK4hq.png" alt="" style="width:350px; height: 233px;" />
  </a>
  <a href="">
    <img src="http://i.imgur.com/gZo0lXk.jpg" alt="" style="width:350px; height: 233px;" />
  </a>
  <a href="">
    <img src="http://i.imgur.com/o0H3If2.png" alt="" style="width:350px; height: 233px;" />
  </a>
   <a href=""> 
    <img src="http://i.imgur.com/p1DFGse.png" alt="" style="width:350px; height: 233px;" />
  </a>
  <a href="">
    <img src="http://i.imgur.com/ck0dtSd.png" alt="" style="width:350px; height: 233px;" />
  <a href="">
  </div>

最后4张图片与前4张相同,因为我有一个动画移动横幅。

1 个答案:

答案 0 :(得分:0)

在您的情况下,您不需要Ajax随机返回,在SQL语句本身中您可以实际获取随机图像。

function getAllImg()
{
    $sql = "SELECT RecipeID, PictureID FROM Pictures ORDER BY RAND() ";

    echo json_encode(executeZParamQuery($sql));
}