【问题标题】:Advanced Call Php Function From Javascript来自 Javascript 的高级调用 PHP 函数
【发布时间】:2013-03-10 07:19:06
【问题描述】:

这是我的代码。

<script>
  function test(div_id) {
    var newMail = '<?php echo count_new_mail($id); ?>';
    setTimeout(test, 10000);
  }
  test();
</script>        

我想要做的是每 10 秒调用一次 php 函数 count_new_mail。当 javascript 由 php 生成时,结果如下所示。

var newMail = 1;

我知道这是因为它运行了 php 并且 count_new_mail 给出的值为 1。如何让这个 javascript 每 10 秒调用一次函数,而不仅仅是保持相同的值?还是我必须将 php 函数编写为 javascript 函数并调用它以获得我想要的结果?

【问题讨论】:

    标签: php javascript


    【解决方案1】:

    PHP 总是在 JavaScript 之前运行,所以让 JavaScript 让 PHP 再次运行的唯一方法是启动另一个请求。 JavaScript 可以通过使用XMLHttpRequest(通常称为 AJAX)来启动请求而无需转到新页面。 JavaScript 代码如下所示:

    // For old versions of Internet Explorer, you need to catch if this fails and use
    // ActiveXObject to create an XMLHttpRequest.
    var xhr = new XMLHttpRequest();
    xhr.open("GET" /* or POST if it's more suitable */, "some/url.php", true);
    xhr.send(null);  // replace null with POST data, if any
    

    这样可以发送请求,但您可能也想获取结果数据。为此,您必须设置回调(可能在您致电 send 之前):

    xhr.onreadystatechange = function() {
        // This function will be called whenever the state of the XHR object changes.
        // When readyState is 4, it has finished loading, and that's all we care
        // about.
        if(xhr.readyState === 4) {
            // Make sure there wasn't an HTTP error.
            if(xhr.status >= 200 && xhr.status < 300) {
                // It was retrieved successfully. Alert the result.
                alert(xhr.responseText);
            }else{
                // There was an error.
                alert("Oh darn, an error occurred.");
            }
        }
    };
    

    需要注意的是send开始请求;它不会等到它完成。有时您必须重组代码以适应这种情况。

    【讨论】:

      猜你喜欢
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      • 2021-12-02
      • 2023-03-18
      • 2021-04-06
      相关资源
      最近更新 更多