php - 同一页面上的 AJAX 调用 $_POST 变量为空
问题描述
我刚刚阅读了很多关于此的主题,但我仍然无法使其工作。将其上传到实时服务器并使用 XAMPP 在 localhost 上进行尝试,仍然发生相同的情况。
在开发者工具/萤火虫上,我可以看到结果,在网络/XHR 上也是如此。任何帮助表示赞赏。
我想将单选按钮提交值与 php 变量进行比较(如 index.php 中所示)在控制台上它按预期工作,但在我的浏览器窗口上却没有。
html.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form name="curso_activo" id="form_preguntas" method="POST" action="" >
<p> option1 </p>
<input id="input_1" type="radio" name="html1" value="a">
<span class="checkmark"></span>
<p> option2 </p>
<input id="input_2" type="radio" name="html1" value="b">
<span class="checkmark"></span>
<p> option3 </p>
<input id="input_3" type="radio" name="html1" value="c">
<span class="checkmark"></span>
<p> option4 </p>
<input id="input_4" type="radio" name="html1" value="d">
<span class="checkmark"></span>
<div class="respuesta_submit">
<input type="submit" id="Respuesta_send" class="button_submit" value="Enviar" name="Enviar_respuesta">
</div>
</form>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"> </script>
<script src="ajax.js"></script>
</body>
</html>
ajax.js
$("#form_preguntas").submit(function (e) {
e.preventDefault();
var question = $("#input_1").attr('name');
var answer = $("input[name=" + question + "]:checked").val();
$.ajax({
type: 'POST',
data: {'param': answer},
success: function (data,) {
console.log(data);
alert(question);
},
error: function () {
console.log('error');
}
});
});
索引.php
<?php
require"html.php";
$correct_answer = 'b';
if ($_POST['param'] == $correct_answer) {
echo "Correct";
}
?>
解决方案
javascript 中的一种可能解决方案,检查响应是否符合您的预期,然后告诉用户:
...
success: function (data,) {
if (data == 'success'){
//do something here
$('#someDiv').html('success!');
}
},
...
推荐阅读
- c# - 如何使许多富文本框的动态字体更小
- javascript - 如何在Jquery中将文本附加到左侧而不是添加到右侧
- sql - 如何选择一组预定义的值及其计数?
- alteryx - 如何将 Alteryx .yxzp 文件解包到较低版本
- wpf - 如何使用 MVVM 模型从 WPF 中的 CheckListBox 中绑定选中/选定项目(我正在使用“WPFToolkit.Extended.dll”来获取 CheckListBox 控件)
- c# - 如何在 C# 的同一个构造函数中初始化同一个类
- terraform - 使用 terraform 在 for_each 嵌套资源中循环
- php - 使用 WordPress 插件中的目录在 URL 上生成自定义输出
- ios - 如何在 UIViewControllerRepresentable Struct 中创建 UIBarButtonItem?
- javascript - 如何在 keyCode 导航的输入中设置自动焦点?