使用表单密钥和AJAX提交表单

3

大家好,我有一个类用于检查通过HTML创建的表单是否有效,并防止表单重复提交(例如按下ctrl+F5)。以下是实现此功能的类:

<?php
class Form_Key
{

protected $oldKey;

public function __construct()
{

    // Ensure we have an available session
    if ( NULL == session_id() )
    {
        session_start();
    }

    // Grab our former key for validation
    if ( isset( $_SESSION['form_key'] ) )
    {
        $this->oldKey = $_SESSION['form_key'];
    }

    // Assign the new key
    $_SESSION['form_key'] = md5( uniqid( mt_rand(), TRUE ) );

}

public function isValid()
{
    return 'POST' == $_SERVER['REQUEST_METHOD']
        && isset( $_POST['form_key'] )
        && '' != trim( $_POST['form_key'] )
        && '' != trim( $this->oldKey )
        && $_POST['form_key'] === $this->oldKey;
}

public function getKey()
{
    return $_SESSION['form_key'];
}

public function getOldKey()
{
    return $this->oldKey;
}

public function render()
{
    return '<input type="hidden" name="form_key" value="' . $_SESSION['form_key'] . '" />';
}

public function __toString()
{
    return $this->render();
}

}  
?>

接下来我有一个表单,看起来大致如下:

require "form_key.php";
$form_key = new Form_Key;
<form action="about.php" method="post" name="create_memory" id="create_memory">
<input type="text" value="" id="lamecaptcha" name="lamecaptcha" />
<input type="text" value="" id="person_name" name="person_name" />
<?php echo $form_key; ?>
</form>

在验证方面(save_memory.php),我会执行以下操作:
require "form_key.php";
$form_key = new Form_Key;
if(isset($_POST) && $form_key->isValid()){
    echo "It is ok to submit";
}else{
    echo "Something went wrong";
}

如果我不通过ajax提交表单,所有的运行都很好,但如果我通过AJAX提交表单,它总是会给我一个"something went wrong"错误。下面是我如何通过AJAX提交表单的代码:

person_name = $("input#person_name").val();
memory = $("input#memory").val();
form_key = $("input#form_key").val();
var html_memory = $.ajax({
type: "POST",
url: "save_memory.php",
data: "person_name=" + person_name + "&memory=" + memory + "&form_key=" + form_key,
async: false
}).responseText;

alert(html_memory);

有什么想法可以解决这个问题,我怎样才能使我的表单通过AJAX提交起来?非常感谢!
1个回答

1
Jquery选择器的键输入无效。您必须将form_key的ID放入其中,如下所示:
 return '<input id="form_key" type="hidden" name="form_key" value="' . $_SESSION['form_key'] . '" />';

[编辑]

另外,您需要调用一个生成输入的函数:

<?php echo $form_key->render(); ?>

1
@Kristian,id的问题你发现得不错。但是输出结果就像它本来的样子一样呈现出来。在第一个代码块中,当对象被打印时,魔术方法__toString会被调用,在第二个代码块中,echo $form_key; 会被执行。 - davogotland

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接