gpt4 book ai didi

javascript - JQuery AJAX 调用 php 函数

转载 作者:行者123 更新时间:2023-11-28 15:16:15 25 4
gpt4 key购买 nike

我正在尝试使用 AJAX 调用替换网页中重新加载 PHP 脚本的页面。

我正在使用 JQuery 来运行 AJAX 脚本,但它似乎没有执行任何操作,因此我尝试编写一个非常基本的脚本来测试它。

我的目录如下

public_html/index.php
/scripts/phpfunctions.php
/jqueryfunctions.js

index.php 包含

<!DOCTYPE html>
<html>
<head>

<!-- jquery functions -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="scripts/jqueryfunctions.js"></script>

<!-- php functions -->
<?php include 'scripts/phpfunctions.php' ?>

</head>

<body>
<button type="button" id="testButt">TEST</button>
</body>

</html>

然后,如果设置了参数,我尝试调用的 phpfunctions.php 页面仅包含回显

<?php

if(isset($_GET["action"])) {
echo "test has been run";
}

?>

我尝试运行的 jqueryfunctions.js 脚本是

$(document).read(function () {
$('#testButt').on('click', function () {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test',
type: 'GET',
success: function (data) {
$('#ajaxdata').html(data);
},
error: function (log) {
console.log(log.message);
}
});
});
});

我看到第一个 console.log 正在调用 jqueryfunctions.js 函数,但它似乎没有调用我的 phpfunctions.php 函数。

我本来希望看到 php echo“测试已运行”,但这并没有发生。

我错过了什么吗?

最佳答案

您应该使用isset()方法:

<?php
if(isset($_GET["action"])) {
if($_GET["action"] == "run_test") {
echo "test has been run";
}
}
?>

如果您使用ajax,那么为什么需要将其包含在索引页面上:

<?php include 'scripts/phpfunctions.php' ?>

我在您的索引页上找不到此元素 $('#ajaxdata')

<小时/>

您还可以检查检查器工具的网络选项卡,以查看对 phpfunctions.php 的 xhr 请求,并查看是否成功或存在任何错误。

关于javascript - JQuery AJAX 调用 php 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33801374/

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