在PHP执行时显示加载图像

时间:2013-09-21 00:04:06

标签: php jquery mysql mysqli jquery-load

我想在php脚本执行时显示加载图像。我已经阅读了关于如何做到这一点的不同答案,但大多数人都表示我应该有一个单独的php页面。但是我使用单页来显示行,那么我怎样才能显示加载图像?

选择查询的示例,我用来获取数据:

 $stmt = $mydb->prepare("select * from table where firstname = ?  and id = ? ");
 $stmt->bind_param('ss', $firstname, $id);
 $stmt->execute();
 $stmt->close();

2 个答案:

答案 0 :(得分:9)

在大多数情况下, 会有两页。第一页,客户端,调用另一个页面,服务器端,并在等待时显示一个非常旋转的东西。当服务器端页面完成加载(当您的查询完成时),您的第一页接收到响应,然后您可以隐藏漂亮的东西,让您的用户知道它已完成。

你可以使用AJAX - 在纯Javascript中或在jQuery中更简单 - 从PHP页面动态加载一些数据并在等待时显示旋转的东西。我在这里使用了jQuery。

<强> CSS

#loading_spinner { display:none; }

<强> HTML

<img id="loading_spinner" src="loading-spinner.gif">

<div class="my_update_panel"></div>

<强>的jQuery

$('#loading_spinner').show();

var post_data = "my_variable="+my_variable;
$.ajax({
    url: 'ajax/my_php_page.php',
    type: 'POST',
    data: post_data,
    dataType: 'html',
    success: function(data) {
        $('.my_update_panel').html(data);
//Moved the hide event so it waits to run until the prior event completes
//It hide the spinner immediately, without waiting, until I moved it here
        $('#loading_spinner').hide();
    },
    error: function() {
        alert("Something went wrong!");
    }
});

PHP (my_php_page.php)

<?php
// if this page was not called by AJAX, die
if (!$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') die('Invalid request');

// get variable sent from client-side page
$my_variable = isset($_POST['my_variable']) ? strip_tags($_POST['my_variable']) :null;

//run some queries, printing some kind of result
$SQL = "SELECT * FROM myTable";
// echo results
?>

答案 1 :(得分:1)

你无法在PHP中真正做到这一点,你必须在JavaScript中做一些事情。所以你可能想要做的是让JQuery显示一个加载微调器,然后对你的PHP作业执行一个AJAX请求,当你获得数据时,隐藏加载指示器。