php 和 javascript 使用 ajax 可以实现进度条吗

发布于 2024-11-02 20:09:16 字数 1498 浏览 5 评论 0原文

我想知道如何像gmail一样制作进度条。

我尝试

<script src="jquery.js"></script>
<script>
$(function (){
    $.ajax({
        url: 'index.php',
        success: function(data) {
            $('#bar').html(data);
        }
    });
})
</script>
<div id="bar"></div>

了在 index.php

[EDIT]: 通过 sleep() 我只是想模拟连续的输出流,就像多线程程序一样php 不支持。

<?php

for($i=0; $i<=10; $i++)
{
    sleep(1);
    echo "$i";
}

似乎输出立即回显,所以我立即得到结果 012345678910

我也尝试过

setInterval(function (){
        $.ajax({
            url: 'index.php',
            success: function(data) {
                $('#bar').html(data);
            }
        });
    }, 1000);

,相反,我在维护 'progress' 的值时遇到了麻烦,所以我将其

<?php

session_start();

if(isset($_SESSION['value'])){
    if($_SESSION['value'] >= 10)
    {
        unset($_SESSION['value']);
    }
    else
    {
        $_SESSION['value']++;
    }
}
else
{
    $_SESSION['value'] = 0;
}

echo $_SESSION['value'];

作为我的 php.ini 的一部分。但看来,我正在连续间隔调用 ajax 函数。

我的问题是,

  1. 在 Gmail 中登录时,Google 如何使用进度条。他们是否像我在第一个示例中尝试的那样获得连续的数据'stream',或者在某个url上发送(定期)请求(尽管不是通过ajax ..通过JSONP或其他方式)并像第二个一样更新页面?

  2. 我可以对 php 做同样的事情吗?即使不是用 php,我可以使用 javascript 和其他支持多线程的服务器端脚本语言来做到这一点吗?

I was wondering how to make progress bar like gmail.

I tried

<script src="jquery.js"></script>
<script>
$(function (){
    $.ajax({
        url: 'index.php',
        success: function(data) {
            $('#bar').html(data);
        }
    });
})
</script>
<div id="bar"></div>

And on index.php

[EDIT]: by sleep() i just meant to simulate continuous stream of output like multithreaded programs which is not supported in php.

<?php

for($i=0; $i<=10; $i++)
{
    sleep(1);
    echo "$i";
}

it seems that output is echoed out at once so i get result 012345678910 at once.

also i tried

setInterval(function (){
        $.ajax({
            url: 'index.php',
            success: function(data) {
                $('#bar').html(data);
            }
        });
    }, 1000);

Instead, i had trouble maintaining value of 'progress', so i did

<?php

session_start();

if(isset($_SESSION['value'])){
    if($_SESSION['value'] >= 10)
    {
        unset($_SESSION['value']);
    }
    else
    {
        $_SESSION['value']++;
    }
}
else
{
    $_SESSION['value'] = 0;
}

echo $_SESSION['value'];

as part of my php. But it seems that, i am calling ajax function on continuous interval.

My Question is,

  1. How does google use progress bar, while loginng in gmail. Do they get continuos 'stream' of data like i tried on my first example or send (regularly) request on some url (though not through ajax .. through JSONP or whatever) and upadate the page like second ?

  2. Can I do same with php , even if not with php, can I do it using javascript and other server side scripting language where multithreading is supported?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

§对你不离不弃 2024-11-09 20:09:16

我不确定 Gmail 对进度条到底做了什么,但您可以在 PHP 中实现类似的功能,尽管可能有点棘手。

首先,解释一下为什么你的例子不起作用:

如果你回显并睡眠,就像你的第一个例子一样,它永远不会起作用。 Ajax 执行完整请求 - 也就是说,如果响应未完成,它将等待。当您循环并睡眠时,请求不会“关闭”,直到 PHP 脚本执行完毕。

如果您使用会话,就像在另一个示例中一样,问题就变成了会话存储。存储通常在脚本执行期间被锁定,并且它不会自行更新以允许进行您想要的进度检查类型。

您可以做的就是手动将进度写入文件(或数据库)。例如:

file_put_contents('progress.txt', 1);

然后,让另一个脚本读取文件并输出内容。

这应该可以工作,因为 file_put_contents 打开、写入和关闭文件。

使用 PHP 之外的其他语言会更容易。多线程可能会让事情变得更容易,但这不是必需的。然而,拥有一个持续运行的进程会让事情变得更简单(PHP 仅在您的请求期间运行一个进程,然后退出)

I'm not sure what exactly Gmail does for the progressbar, but you can achieve something similar in PHP, although it may be a bit tricky.

First, to explain why your examples don't work:

If you echo and sleep, like your first example, it will never work. Ajax performs a full request - that is, if the response does not finish, it will wait. When you loop and sleep, the request is not "closed" until the PHP script has finished executing.

If you use session, like in the other example, the problem becomes the session store. The store is typically locked during script execution, and it will not update itself to allow for the type of progress check you want.

What you could do is write progress to a file (or to a database) manually. For example:

file_put_contents('progress.txt', 1);

Then, have another script read the file and output the contents.

This should work, because file_put_contents opens, writes and closes the file.

Using some other language than PHP would make it easier. Being multithreaded would possibly make it easier, but is not a requirement. However, having a continuously running process would make it simpler (PHP only runs a process for the duration of your request and then exits)

灯角 2024-11-09 20:09:16

每隔一段时间运行 jquery 代码,然后使用 PHP 打印进度百分比并绘制条形图。

所以它会像

<script>
function bar()
{
 var v=getProgress(...);
 setTimeout("bar()",1000);
 drawBar();
}

function drawBar(l)
{
 //set div's length to l
}
</script>

编辑2

<?php
/* get the request and calculate the job completion percentage and echo it !  */
?>

run your jquery code at an interval, and use PHP to print the progress percenage and draw the bar then.

so it will be something like

<script>
function bar()
{
 var v=getProgress(...);
 setTimeout("bar()",1000);
 drawBar();
}

function drawBar(l)
{
 //set div's length to l
}
</script>

EDIT 2

<?php
/* get the request and calculate the job completion percentage and echo it !  */
?>
醉生梦死 2024-11-09 20:09:16

我认为 Gmail 在加载所有资源(例如 JS 文件)时会显示进度。有不同的方法可以做到这一点:您可以使用 JS 动态包含所有资源,或者可以让所有包含的 JS 文件报告它们已加载。


要使 PHP 输出部分输出,请使用:

ob.php

<?php

ob_start();

for ($i = 0; $i < 100; $i++) {
    echo "{$i}<br />";

    ob_flush();
    flush();

    usleep(100000);
}

.htaccess

php_value output_buffering "0"

I think Gmail shows progress when it loads all resources, like JS files. There are different ways to do this: you could dynamically include all resources with JS, or you could make all included JS files report that they've been loaded.


To make PHP output partial output, use this:

ob.php

<?php

ob_start();

for ($i = 0; $i < 100; $i++) {
    echo "{$i}<br />";

    ob_flush();
    flush();

    usleep(100000);
}

.htaccess

php_value output_buffering "0"
高速公鹿 2024-11-09 20:09:16

此线程和 此链接 帮助我找到了同一问题的解决方案,因此我提供它郑重声明:

test.php:

<?php 
  for($i=0; $i<100; $i++)
  {   usleep(100000); //100ms
      echo 'A'; ob_flush(); flush();
  }
?>

test.html:

<body>
   <button onclick='call()'>call</button>
   <div id='progress'>...</div>
   <script>
      function fprogress(e) 
      { document.getElementById('progress').innerHTML ='progress: '+e.loaded +'%'; }
      function call()
      {  var req = new XMLHttpRequest();  
         req.addEventListener("progress", fprogress, false);
         req.open('GET', 'test.php', true);  req.send(null);
      }
   </script>
</body>

... 所以 test.php 可以是任何执行某些操作的作业...并且在执行此操作时使用闪烁缓冲区回显 100 个字符(字节)。

this thread and this link helped me to find out solution for the same problem, so i am providing it for the record:

test.php:

<?php 
  for($i=0; $i<100; $i++)
  {   usleep(100000); //100ms
      echo 'A'; ob_flush(); flush();
  }
?>

test.html:

<body>
   <button onclick='call()'>call</button>
   <div id='progress'>...</div>
   <script>
      function fprogress(e) 
      { document.getElementById('progress').innerHTML ='progress: '+e.loaded +'%'; }
      function call()
      {  var req = new XMLHttpRequest();  
         req.addEventListener("progress", fprogress, false);
         req.open('GET', 'test.php', true);  req.send(null);
      }
   </script>
</body>

... so test.php can be any JOB which doing some stuff... and while doing it ECHOes 100 characters (bytes) with flashing buffer.

哀由 2024-11-09 20:09:16

根据我的意见,您可以将登录过程分为几个部分并进行检查。

每个零件检查完成后都会向进度条发送响应,进度条宽度会增加此类模式。之后,进度条将向您的登录过程发送下一个请求,直到您无法达到 100% 登录和重定向为止。

As per my opinion, you can divide your login process in several parts and checks.

Every part check completed send response to your progress bar and progress bar width will increase such patterns. After that progress bar will send next request to your login process for step untill you will not get upto 100% login and redirect.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文