从Javascript高级调用Php函数

从Javascript高级调用Php函数,php,javascript,Php,Javascript,这是我的密码 <script> function test(div_id) { var newMail = '<?php echo count_new_mail($id); ?>'; setTimeout(test, 10000); } test(); </script> 我知道这是因为它运行了php,count_new_mail的值为1。如何让这个javascript每10秒调用一次函数,而不只是保持相同的值?或

这是我的密码

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

我知道这是因为它运行了php,count_new_mail的值为1。如何让这个javascript每10秒调用一次函数,而不只是保持相同的值?或者我必须将php函数编写为javascript函数并调用它才能得到我想要的结果吗?

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(){
//只要XHR对象的状态发生变化,就会调用此函数。
//readyState为4时,它已完成加载,这就是我们所关心的
//大约。
if(xhr.readyState==4){
//确保没有HTTP错误。
如果(xhr.status>=200&&xhr.status<300){
//已成功检索。请通知结果。
警报(xhr.responseText);
}否则{
//有一个错误。
警报(“哦,该死,发生了一个错误。”);
}
}
};

需要注意的是,
send
只启动请求;它不会等到完成。有时,您必须重新构造代码以适应这种情况。

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(){
//只要XHR对象的状态发生变化,就会调用此函数。
//readyState为4时,它已完成加载,这就是我们所关心的
//大约。
if(xhr.readyState==4){
//确保没有HTTP错误。
如果(xhr.status>=200&&xhr.status<300){
//已成功检索。请通知结果。
警报(xhr.responseText);
}否则{
//有一个错误。
警报(“哦,该死,发生了一个错误。”);
}
}
};
需要注意的是,
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.");
        }
    }
};