如何实时传递变量?

时间:2014-04-23 05:05:51

标签: php jquery ajax

我有一个简单的代码: ajax.html

<html>
<head>
<title>AJAX</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
    $(document).on("click", "#ajax-button", function() {
        $.ajax({type: 'POST', url: 'ajax.php', data: ({ ajax: $('input[name="ajax"]').val() }), 
                success:function(data){
                    $('#result-ajax').html(data);
                } 
        });
    });
});
</script>
<input type="text" name="ajax" /> <button id="ajax-button">OK</button>
<div id="result-ajax"></div>
</body>
</html>

ajax.php

<?php
$ajax = intval($_POST['ajax']);

for ($i=0; $i < $ajax; $i++) {
    echo $i;
    sleep(3); 
}
?>

我想实时变量,但现在我在循环后得到变量,我如何实时更新我的​​变量?我尝试设置async: false,但它只是冻结窗口浏览器。

1 个答案:

答案 0 :(得分:0)

HTTP用作请求 - 响应协议,因此您无法在不发出新请求的情况下每3秒响应一次服务器。另一种方法是使用sockets。我希望它有用。