gpt4 book ai didi

javascript - 在 PHP、JAVASCRIPT 上使用 AJAX 检查数据库中的变量,如果为真,则为某个页面的标题

转载 作者:行者123 更新时间:2023-11-30 00:27:25 26 4
gpt4 key购买 nike

我正在尝试使用 AJAX 检查数据库中的变量,如果它是真的,那么它应该使它成为某个页面的标题,除了在这个测试短语中,我没有检查任何变量。如果我调用该函数,我只是在测试它是否会转到该特定页面。我从 test1.php 开始,但它应该已经调用了 ajax 函数,并立即转到 test3.php,但它没有。我不确定我做错了什么。请看一下我的代码:

ajax.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script type = "text/javascript">

function nopassAjax(url,timeout) {

$.ajax({
type: "POST",
url: url,
error: function(xhr,status,error){alert(error);},
success:function(data) {
setTimeout(function() { nopassAjax(url,timeout); }, timeout);
}

});

}

</script>

test1.php

<?php

include('ajax.php');

echo "<script>";

echo "nopassAjax('test2.php',1000);";

echo "</script>";

?>

test2.php

<?php

//checks some stuff in the database
//if true, header off to test3.php

header("Location: test3.php");

?>

test3.php

<?php

echo "Hello";

?>

最佳答案

这不会像您预期的那样工作。将发生的是,当您点击 test1.php 时,它将触发 nopassAjax(),这将向 test2.php 发出 AJAX 请求. test2.php 脚本将调用 header("Location: test3.php"); 但作为对 AJAX 请求的响应,所以它是 nopassAjax() 将接收 test3.php 的内容,而不是调用页面 test1.php。然后你 setTimeout 重新开始,所以它会在一个循环中,永远不会到达你想要的地方。

我建议你做一些不同的事情。进行从 test1.phptest2.php 的 AJAX 调用,但从那里返回一个包含数据库信息的 JSON 对象。当 test1.php 收到它时,它会检查数据并决定是否重定向。

可能是这样的:

test1.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script type = "text/javascript">
$(document).ready(function() {
setMonitoring("test2.php", 100);
});

function setMonitoring(url, timeout) {
setTimeout(function(){
checkData(url);
}, timeout);
}

function checkData(url) {
$.ajax({
type: "POST",
url: url,
dataType: "json", // type of data that you're expecting back from the server
error: function(xhr,status,error){alert(xhr.status + " - " + error);},
success:function(data) {
if (data.redirect) {
window.location.href = data.redirectTo;
}
setMonitoring(data.nextUrlToQuery, data.timeout);
}
});
}
</script>

test2.php

// retrieve the information you need...

$result = array(
"redirect"=>false,
"nextUrlToQuery"=>"test2.php",
"redirectTo"=>"test3.php",
"timeout"=>1000
);
echo json_encode($result);

test3.php

echo "Hello";

在此示例中,当您将 test2.php 中的 redirect 更改为 true 时,页面将重定向到 test3.php

关于javascript - 在 PHP、JAVASCRIPT 上使用 AJAX 检查数据库中的变量,如果为真,则为某个页面的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30904418/

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