Ajax 实时更新,无需刷新 PHP 页面


ajax real time updates without refreshing a php page

我正在尝试将一些数据发布到post.php,我希望结果以form.html显示,我使用 Ajax 获取 php 输出而无需重新加载页面,我无法弄清楚如何在 php 脚本完成之前刷新一些 php 输出。

我尝试了flush()ob_flush()但似乎它们在与 Ajax 一起使用时不起作用。我的目标是实时更新form.html而无需重新加载页面。

以下是我想要实现的目标的一个例子。源代码:

形式.html

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("#myform").validate({
                submitHandler: function(form) {
                    // do other stuff for a valid form
                    $.post('post.php', $("#myform").serialize(), function(data) {
                        $('#results').html(data);
                    });
                }
            });
        });
    </script>    
</head>
<body>
    <form name="myform" id="myform" action="" method="POST">  
    <!-- The Name form field -->
        Name:
        <input type="text" name="name" id="name" size="30" value=""/>  
        <br>
    <!-- The Email form field -->
        Email:
        <input type="text" name="email" id="email" size="30" value=""/> 
        <br>
    <!-- The Submit button -->
      <input  type="submit" value="Submit"/></div>
    </form>
    <!-- Result goes here -->
    <div id="results"><div>
</body>
</html>

帖子.php

<?php
for($i=0;$i<2;$i++) {
    echo "Your Name is ".$_POST['name']. "<br/>";
    echo "Your E-mail is".$_POST['email']."<br/>";
    echo "Waiting 2s <br/><br/>";
    //I want to print the above before waiting 2 seconds.
    sleep(2);// in real application this will be equivalent of some calculation that takes time.
}
?>

您的回显可能已经发送到客户端浏览器,但客户端将继续等待进一步的输出,直到您的 PHP 脚本实际完成。您需要尽早断开客户端的连接,例如:在sleep(2)之前。试试这个:

    ignore_user_abort(true);
    // Disconnect with the client
    if (!connection_aborted()) {
        $response = 'your response';
        header('Content-Length: ' . strlen($response));
        header('Connection: close');
        echo $response;
        flush();
    }

请注意,请不要在上述代码块之前进行其他回显。所有输出都应以 $response 为单位,因为必须正确计算Content-Length

您不能简单地以多个顺序输出的形式返回单个页面请求,因为每个页面加载(可能是来自浏览器的普通 HTTP 请求或脚本明智的 AJAX 请求)是客户端请求页面和服务器传递匹配文档的结果。它不仅仅是PHP生成和交付输出,它是独立于给定请求资源的性质而满足页面请求的Web服务器,并且它不会提供半完成的页面。


这可能是您最初想法的替代方法:AJAX 样式的多步骤操作示例:

后端:邮编.php:

<?php
echo "Your Name is ".$_POST['name']. "<br/>".
     "Your E-mail is".$_POST['email']."<br/>".
     "Will now continue with calculation job ...";
// store the values inside db, create session and return content
...

后计算.php

<?php
// longer running script doing stuff
...
print 'Done.';

前端:

按如下方式修改脚本:

<script type="text/javascript">
    $(document).ready(function(){
        $("#myform").validate({
            submitHandler: function(form) {
                // do other stuff for a valid form
                $.post('post.php', $("#myform").serialize(), function(data) {
                  // will return the content from post.php    
                  $('#results').html(data);
                  // now call the second process
                  $.ajax('post-calculation.php', {
                    success: function(result) {
                      $('#results').append(result);
                    }
                  });
                });
            }
        });
    });
</script>  

言论:

这应该被视为一个示例,而不是如何使用多步骤操作执行 AJAX 调用的良好做法。建议使用允许脚本对调用后端脚本时可能发生的错误做出反应的输出格式,即不返回 HTML 代码而是返回 JSON [1]。您可能希望将早期接收的数据的某些部分存储在 $_SESSION 变量中,以便之后在以后运行的脚本中重用这些数据,不要忘记在访问会话对象之前始终调用 session_start();

[1] http://www.sitepoint.com/ajaxjquery-getjson-simple/(简单教程)