【问题标题】:How do I determine if a HTML-form answer is correct (calling PHP via $.post), without revealing the answer?如何确定 HTML 形式的答案是否正确(通过 $.post 调用 PHP)而不透露答案?
【发布时间】:2020-09-09 00:24:32
【问题描述】:

我正在做一个填空测验 (current state)。在我的index.php 中,我想验证用户input 是正确的答案(例如,它与我的 MySQL 服务器中的内容匹配)。

我可以通过<?php echo ... ?>-ing 来验证答案是否正确,但这会导致答案在 html 文件中,这具有允许作弊的缺点。

我从this answer 收集到,我需要使用类似$.post('file.php', {variable: variableToSend}); 的东西,所以我尝试这样做:

<script>
    function process_guess() {
        var input = [...snip...];

        [...snip...]

        var is_correct = $.post('process_answer.php', {guess: input});

        [...snip...]

        if(is_correct == 1) {
            [...snip...]
        }
        else {
            [...snip...]
        }
    }
</script>

上面的 Javascript 函数是从我 index.php 的其他地方的 html 表单调用的;我可以使用console.log 来验证上面的input 变量是实际的用户输入。但是,从console.log来看,我使用$.post的方式是完全错误的,但我不确定正确的语法是什么。

process_answer.php 我有:

<?php
    if($_POST['guess'] == $problem_data["answer"]) echo "1";
    else echo "0"; 
?>

我不知道如何从这里开始。

问题:如何确定 HTML 形式的答案是否正确(通过 $.post 调用 PHP),而不透露答案?

【问题讨论】:

  • 所以将答案发布到服务器,让服务器检查它是否正确。让服务器返回一个布尔值
  • 是的,这就是我想要做的。我只是没有成功。
  • 我认为您可能需要做的是在检查之前json_decode PHP 中的响应,因为您在 $.post 中传递了一个 JSON 对象
  • $.post('process_answer.php', {guess: input}).done(function(xxx) { console.log(xxx); });
  • @aljx0409 OP 没有发布 JSON。这就是 jQuery 发布 application/x-www-form-urlencoded 数据的方式

标签: javascript php forms


【解决方案1】:

你的方法很好。 ajax 调用是一个很好的方法。

在 Javascript 中,根据the documentation,您只需等待服务器响应。但是您必须注意这是异步的(因此下面的代码可能会在您的回调之前执行)。我提出了类似的建议。

$.post('process_answer.php', {guess: input})
  .done(function( data ) {
    // Execute your logic inside the request callback
    if(data) {
        [...snip...]
    }
    else {
        [...snip...]
    }
  }
);

在你的 php 中,我建议退出脚本或简单地返回一个值

<?php
// return a json encoded boolean
header('Content-type: application/json');
echo json_encode($_POST['guess'] == $problem_data["answer"]);die;
?>

在菲尔的评论后编辑:

Phil 是对的,我已经更新了我的示例。

【讨论】:

  • PHP 需要echo,而不是return。我还会在回复中添加header('Content-type: application/json')json_encode()
  • @Phil 你说得对,经过快速测试,回报是不够的。使用框架的坏习惯:)
猜你喜欢
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 2022-11-13
  • 1970-01-01
  • 2020-01-16
  • 1970-01-01
  • 1970-01-01
  • 2018-06-28
相关资源
最近更新 更多