我有一个关于在哪里放置脚本和变量的顺序的问题。原因是我认为如果您有一个函数,并且在加载页面之后调用它,那么它将被“找到”并执行。
我有一个简单的POST示例,两个php页面,php变量在脚本之前设置:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="/digiblox/css/style.php" rel="stylesheet">
<script src="/digiblox/functions/jquery-3.6.0.js"></script>
<script>
<?php $startRow2send = rand(); ?>
function firstPage() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("ajaxCall").innerHTML = this.responseText;
}
xhttp.open("POST", "postRec.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("startRow2send=" +<?php echo $startRow2send; ?>);
}
</script>
</head>
以及本页的正文:
<body>
<p>
<div><button type="button" onclick="firstPage()">Test ajax call</button> </div>
</p>
<div id="ajaxCall">
</div>
</body>
</html>
因此,它调用一个简单的页面并输出“POST方法发送的值是:”和值。
我的问题是,如果我将php变量设置得更低,比如在页面的正文中,那么脚本就无法工作。
如果我把脚本放在页面的底部,它和works.So类似于php包含,它基本上是按照代码中显示的顺序读取的,这是可以理解的,但是函数或脚本的目的肯定是声明它,然后在按下按钮时调用它。
是否有一种方法可以将脚本、函数保存在标头部分,并使用仅在加载脚本后才加载的加载变量调用它们。
同时,按钮不应该每次都“刷新”Ajax调用吗?
发布于 2022-01-28 15:22:21
页面及其内容从上到下呈现。所以,如果你调用变量X,你必须先声明它,然后叫它=>,这应该是关于顺序的答案。现在关于Ajax和php。php代码只呈现一次,因为这就是它应该如何工作的方式。AJAX的发明使得开发人员可以调用/访问服务器端变量,而无需重新加载整个页面(您在这里所做的)。问题是,您正在混合AJAX和PHP:您的php变量$startRow2send将只有一个值。我想您也希望这个PHP变量值随AJAX调用而改变。为此,您应该了解AJAX调用只调用JAVASCRIPT函数。firstPage()。PHP变量在重新加载页面之前保持不变。PHP/HTML只呈现一次页面,仅此而已。AJAX/JS可以执行更多的操作,因为它们是在浏览器(本地)中运行的。因此,也许您应该将php变量更改为javascript变量,并将其放入函数中。然后,每次调用时,您的变量都会发生变化。
// you can use this function to generate a random number in Javascript
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
// then in your original function you can add
function firstPage() {
// generate a random between 100 and 999
var myJSRandomNr = getRandomArbitrary(100, 999)
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("ajaxCall").innerHTML = this.responseText;
}
xhttp.open("POST", "postRec.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("startRow2send=" + myJSRandomNr );
}
https://stackoverflow.com/questions/70900675
复制