首页 > 解决方案 > 同一页面上的 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";
}

?>

标签: phphtmlajaxpost

解决方案


javascript 中的一种可能解决方案,检查响应是否符合您的预期,然后告诉用户:

...

success: function (data,) {
  if (data == 'success'){
     //do something here
     $('#someDiv').html('success!');
  }
},

...

推荐阅读