【发布时间】:2022-01-29 07:22:21
【问题描述】:
我有一个关于放置脚本和变量的顺序的问题。原因是我认为如果你有一个函数并且在页面加载后调用它,它将被“找到”并执行。
我有一个简单的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 变量设置得更深,比如在页面的正文中,那么脚本就不起作用了。
如果我把脚本放在页面底部,它就可以工作。所以就像 php include 一样,它基本上是按照它在代码中出现的顺序读取的,可以理解,但函数或脚本的重点肯定是声明它当按下按钮时它会被调用。
有没有办法将脚本、函数保留在标题部分中,并使用加载的变量调用它们,这些变量仅在加载脚本后加载。
同时,按钮不应该每次都“刷新” Ajax 调用吗?
【问题讨论】: