Symfony2的形式与CSRF通过JQuery的AJAX形式、CSRF、AJAX、JQuery

2023-09-10 15:59:42 作者:有妞不泡,大逆不道

我开发一个评论框,将通过JQuery的AJAX调用保存注释。

I am developing a comments box that will save the comment through a JQuery AJAX call.

JQuery的

下面是JQuery的code对于(本作品无缝):

Here's the JQuery code for that (this works seamlessly):

$(".post-comment").click(function() {
    var $form = $(this).closest("form");

    if($form)
    {
        $.ajax({
            type: "POST",
            url: Routing.generate('discussion_create'),
            data: $form.serialize(),
            cache: false,
            success: function(html){
                alert("Success!");
                // Output something                  
            }
        });
    }
    else
    {
        alert("An error occured");
    }
    return false;   
});

Symfony2的控制器

在Symfony2的控制器方法,然后拿起表格数据,并对其进行处理。作为这一过程的一部分,它会检查,看看是否形式是有效的:

The Symfony2 controller method then picks up the form data and processes it. As part of that process it checks to see if the form is valid:

$entry = new Discussion();
$discussionForm = $this->createForm(new DiscussionType(), $entry);

if ($request->getMethod() == 'POST') {

    $discussionForm->bindRequest($request);

    if ($discussionForm->isValid()) {

此检查不会返回true。在别的我什么解压错误消息已给出,并得到:

This check is not returning true. In the else I extract what error messages have been given and get:

Array
(
    [0] => The CSRF token is invalid. Please try to resubmit the form
)

该CSRF令牌被通过后,就像它将如果形式同步提交通过。

The CSRF token is being passed via post just as it would if the form was submitted synchronously.

另一个可能的问题..独特的形式标识的

我使用的形式是由一个表单类型类创建。在任何给定的页面会出现若干意见的形式。作为Symfony2的使用类型类填充表单ID属性的getName()方法,我已经修改了它,像这样:

The form I am using is created by a form type class. On any given page there will be several comments forms. As symfony2 uses the getName() method of the type class to populate the forms ID attribute, I have modified it like so:

public function getName()
{
    return 'discussionForm' . $randomNumber;
}

这使得多个注释的形式没有相同的ID,例如discussionForm20,discussionForm21,discussionForm22等。

This allows multiple comments forms without the same id e.g. discussionForm20, discussionForm21, discussionForm22 etc.

我可以删除该组合中的Symfony2表单组件,并使用标准的PHP逻辑生成表单/流程提交,但我忍住了现在。

I could remove the symfony2 Form component from the mix and generate the form / process the submission using standard PHP logic but I'm resisting that for now.

有谁知道为什么形式CSRF令牌是无效的?如何对此有何建议,可以修改,或者你是怎么做到的?

Does anyone know why the forms CSRF token is invalid? Any suggestions on how this could be modified or how you do it?

推荐答案

试着使用适当的jQuery函数:提交()^^在我的解决方案,我想,你的表单ID为comment_form。适用于所有我的SF2项目:

Try with the adequate JQuery function: submit() ^^ In my solution I suppose that your form has the id "comment_form". Works on all my sf2 projects:

$('#comment_form').submit(function(e) {

    var url = $(this).attr("action");

    $.ajax({
        type: "POST",
        url: url, // Or your url generator like Routing.generate('discussion_create')
        data: $(this).serialize(),
        dataType: "html",
        success: function(msg){

            alert("Success!");

        }
    });

    return false;

});

在CSRF场通常会被发送!

The CSRF Field would normally be sent !

不要忘了添加{{form_rest(表)}}树枝标签在您的表单模板,将生成所有隐藏的领域像CSRF。

And don't forget to add the twig tag {{ form_rest(form) }} in your form template, that will generate all hidden field like CSRF.