来自Javascript的高级呼叫Php功能

时间:2013-03-10 07:19:07

标签: php javascript

这是我的代码。

<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函数并调用它以获得我想要的结果?

1 个答案:

答案 0 :(得分:3)

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只有启动请求;它不会等到它完成。有时您需要重新构建代码以适应它。