[英]Why does PHP AJAX work as from second click only?
PHP 和 AJAX 的新手。
我制作了一个基本页面,当我单击一个按钮时,一个 php 页面将连接到数据库并返回年龄为 45 岁的人的姓名(发送时已包含在 url 中)。
我唯一的问题是,它只在我第二次单击按钮时起作用。 请帮忙?
我的 ajax.html 和 ajax-example.php 代码如下:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
ajaxRequest = new XMLHttpRequest();
function ajaxFunction() {
ajaxRequest.onreadystatechange = reaction();
ajaxRequest.open("GET","ajax-example.php?age=45", true);
ajaxRequest.send(null);
}
function reaction() {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
alert(ajaxRequest.responseText);
}
}
</script>
<button onclick="ajaxFunction();">Click me</button>
</body>
</html>
<?php
$server = "localhost";
$user = "root";
$password = "";
$db = "ajaxtrial";
$conn = mysqli_connect($server,$user,$password,$db);
if (!$conn) {
die('Failure to connect!');
}
$age = $_GET['age'];
$sql = "SELECT name FROM ajax_example WHERE age =".$age;
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$display = "The name is ".$row['name'];
}
echo $display;
?>
删除您分配给onreadystatechange
的reaction
方法的括号。
<script type="text/javascript">
ajaxRequest = new XMLHttpRequest();
function ajaxFunction() {
ajaxRequest.onreadystatechange = reaction;
ajaxRequest.open("GET","ajax-example.php?age=45", true);
ajaxRequest.send(null);
}
function reaction() {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
alert(ajaxRequest.responseText);
}
}
</script>
或者您可以将匿名函数初始化为onreadystatechange
。
<script type="text/javascript">
ajaxRequest = new XMLHttpRequest();
function ajaxFunction() {
ajaxRequest.onreadystatechange = function(){
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
alert(ajaxRequest.responseText);
}
}
ajaxRequest.open("GET","ajax-example.php?age=45", true);
ajaxRequest.send(null);
}
</script>
我希望这对你有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.