gpt4 book ai didi

php - 从 Javascript 高级调用 PHP 函数

转载 作者:行者123 更新时间:2023-11-28 20:36:13 26 4
gpt4 key购买 nike

这是我的代码。

<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 运行,因此让 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启动请求;它不会等到完成。有时您必须重组代码以适应这种情况。

关于php - 从 Javascript 高级调用 PHP 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15319896/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com