javascript - 运行 PHP 脚本时显示加载图像

标签 javascript php jquery html ajax

我一直在阅读这个问题的答案,但我不明白。主要是因为我对 AJAX 和 javascript 的了解为零。

我有一个带有按钮的页面,当用户单击该按钮时...PHP 脚本会扫描服务器中的文件夹并使用数据库执行各种操作。

我想在发生这种情况时显示加载 gif。用户不发送信息或接收任何内容,只需单击按钮即可。

我的第一次尝试是将用户发送到 php 文件...就像这样(只是一个例子)。并放置一个在 DOM 加载时显示图像的 div。 但这不起作用,事实上,它甚至没有显示空白页面,我仍然可以看到单击按钮的页面,并且因为 php 脚本的末尾有一个重定向,所以我只看到加载浏览器图标作为正在发生的事情的指示器。

<html>
    <head>
        <title></title>
        <script type="text/javascript">
            $(window).load(function() {
                $(".loader").fadeOut("slow");
            })
        </script>
        <style type="text/css">
            .loader {
                position: fixed;
                left: 0px;
                top: 0px;
                width: 100%;
                height: 100%;
                z-index: 9999;
                background: url('images/page-loader.gif') 50% 50% no-repeat rgb(249,249,249);
            }
        </style>
    </head>
    <body>
        <div class="loader"></div>
        <!-- PHP SHOULD DO STUFF HERE THEN REDIRECT BACK TO WHERE THE BUTTON WAS CLICKED-->
    </body>
</html>

我知道我必须将 php 部分与“ View ”部分分开。所以我的问题是...如何让按钮显示加载 gif...同时以某种方式从服务器端运行 php 脚本。

我也尝试过:

<script type="text/javascript">
$('#buttonid').click(function(){
  $('.loader').show();
  $.ajax({
   type: 'POST',
   url: 'script.php',
   success:function(result){
       $('.loader').hide();
   }
}
</script>

但它也不起作用。我禁用了脚本上的重定向,当它完成运行时,它会将我带到该页面,而不是停留在我发出调用的页面上。

最佳答案

您展示的 Javascript 很好,并且是正确的方法。不要重定向到任何地方,不要包含任何其他 JS。如果我理解正确的话:

I disabled the redirection on the script and when it finishes running it takes me to that page instead of remaining on the one I made the call from.

您的意思是单击按钮会将您发送至script.php 。您尚未包含按钮 HTML,但我猜您的按钮位于 <form> 内。当您单击它时,您的 jQuery click处理程序被触发,但表单也被提交,就像你根本没有 JavaScript 一样。这会将您发送至 script.php ,这就是您所看到的。

您需要停止默认表单提交,以便仅触发您的 Javascript 处理程序。您可以按如下方式执行此操作:

// Event handlers are passed an event object as a parameter
$('#buttonid').click(function(e){

  // Prevent the normal action this event would cause, in this case 
  // submitting the form
  e.preventDefault();

  // ... continue with the rest of your code
  $('.loader').show();

更多信息请参见 the jQuery docs .

关于javascript - 运行 PHP 脚本时显示加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41858589/

相关文章:

javascript - db.collection findOne by id 运行但不返回

javascript - 上传图片到tinyMCE

Jquery .trigger ('stop' ) .draggable 的方法

jquery - fullpage.js 菜单从固定底部到固定顶部

javascript - PHP数据库查询: How to return the results from a while loop to a Javascript Variable?

javascript - 在 Angular 中使用 ViewChild() 获取元素

php - 带有 omnipay 的 CodeIgniter 自定义值

php - 需要帮助找出 MySQL 查询来计算某个数字

php - 用于托管 PHP 网站的 Docker 架构

javascript - 如何检查文本框中的值,如果它在 3 秒内没有更改,则执行某些操作,否则在 3 秒后再次检查?