javascript - Ajax jquery mysqli 更新

标签 javascript php jquery ajax

我正在尝试做一个 Ajax 演示来自学这个概念,但我就是做不到。

我要获取的示例是在第一页上取一个变量(在本例中为绿色),如果单击了绿色按钮,则在 ajax 处理页面上使用它以某种方式记录绿色单击按钮(当前在错误日志中,然后我将继续将其存储在数据库中)。

理想情况下,我希望能够重复使用相同的代码段将变量更改为红色,并让错误日志报告按下了红色按钮。

我已经使用 location.reload 和随机数向自己证明了 javascript 正在执行,并且页面在每次加载时都不同。

我根本不是 JavaScript 专家,您可能看得出来。我需要先声明 a 变量还是完全声明其他变量?

uglytest.php

<script src="https://code.jquery.com/jquery-2.2.3.js"></script>
<!-- jQuery Ajax -->
<script type="text/javascript">
function clickyes(a) {
$.ajax({
       type: "POST",
       url: "./ajax.php",
       data: {"test":a},
       success: function (response) {
       default = $("#default").val();
       });
    location.reload();
}
</script>

<script type="text/javascript">
function clickno() {
    location.reload();
}
</script>


<?
echo mt_rand(0,99);
$result = "green"; 

echo "<p><form>here's a $result button. Do you want click on it?</p>";
echo "<button onclick=\"clickyes(" . $result . ")\" style=\"background-color: $result; \">Yes</button>";
echo "<button onclick=\"clickno()\">No</button></form>";

?>

ajax.php

<?
  $test = $_POST['test'];
   error_log($test, 0);
?>

最佳答案

此处 location.reload 将在不等待 ajax 请求的情况下被调用,因为 ajax 是一个异步函数。这可能是问题所在。在ajax响应成功时保持reload。

function clickyes(a) {
$.ajax({
       type: "POST",
       url: "./ajax.php",
       data: {"test":a},
       success: function (response) {
       default = $("#default").val();
       location.reload();
       });

}


Also Change this: 
echo "<button onclick=\"clickyes('" . $result . "')\" style=\"background-color: $result; \">Yes</button>";

关于javascript - Ajax jquery mysqli 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36763525/

相关文章:

javascript - 使用 AJAX 运行 PHP 表单

javascript - AJAX POST 查询失败并显示 UNKNOWN_PROTOCO

javascript - 将 wordpress 中的样式表和脚本与 functions.php 链接起来

javascript - 如何在另一个php中使用javascript getElementById?

jquery - 通过 jQuery ajax 调用 JSF 操作

javascript - Vue 未定义,即使已导入

javascript - FileReader.readAsDataURL 上传到 express.js

javascript - 数据表激活单单元格编辑 onclick(第 2 部分)

php - 类别未放置在正确的部分

javascript - 为什么 "load"不起作用?