Symfony2:CSRF令牌无效.请尝试重新提交表格 [英] Symfony2: The CSRF token is invalid. Please try to resubmit the form

查看:133
本文介绍了Symfony2:CSRF令牌无效.请尝试重新提交表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,必须在字段中填写一些信息. 即使我在里面放东西,也会出现错误:

I have a form wher I have to fill in some information in a field. Even if I put something inside, I am getting the error:

The CSRF token is invalid. Please try to resubmit the form

有关此问题: symfony2 CSRF无效我正确使用了$ form-> bindRequest( )

Related to this question: symfony2 CSRF invalid I am using correctly the $form->bindRequest()

if ($this->getRequest()->getMethod() == 'POST') {
   $form->bindRequest($this->getRequest());
   if ($form->isValid()) 
   {
       ...
   }

这是我的模板(树枝)代码:

Here is my template (twig) code:

<div class="item item-last">
<h1>Create Affiliation</h1>

{% if valid == false %}
    <div class="error">
        {{ form_errors(form) }}
        {{ form_errors(form.affiliation) }}
        {{ error }}
    </div>
{% endif %}
{% if app.session.flash('user-notice') != '' %}
<div class="flash-notice">
    {% autoescape false %}
    {{ app.session.flash('user-notice') }}
    {% endautoescape %}
</div>
{% endif %}

</div>
<div class="item item-last">
<form action="{{ path('SciForumVersion2Bundle_user_submission_affiliation_create', {'hash_key' : submission.hashkey, 'author_id' : author.id }) }}?ajax=no" method="POST" class="authorForm" {{ form_enctype(form) }}>
    <div style="float:left;">
        <table width="100%" cellspacing="0" cellpadding="0">
            <tr>
                <td>
                    {{ form_label(form.affiliation) }}
                </td>
                <td>
                    {{ form_widget(form.affiliation, { 'attr': {'size': 40} }) }}
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;
                </td>
                <td>
                    <div class="button button-left button-cancel">
                        <img src="{{ asset('bundles/sciforumversion2/images/design/new/button-red.png') }}"/>
                        <a href="{{ path('SciForumVersion2Bundle_user_submission_author_edit', { 'hash_key' : submission.hashkey, 'author_id' : 0 }) }}" class="submission_link">cancel</a>
                    </div>
                    <div style="float: left;">&nbsp;</div>
                    <div class="button button-left button-cancel">
                        <img src="{{ asset('bundles/sciforumversion2/images/design/new/button.png') }}"/>
                        <input type="submit" name="login" value="submit" />
                    </div>
                    <div style="clear: both;"></div>
                </td>
            </tr>
        </table>
    </div>
{{ form_rest(form) }}

</form>
</div>

这是js代码:

function init_submission_functions()
{

init_fck();

$(".submission_link").unbind("click").bind("click", function() {

    var href = $(this).attr("href");
    if( href == null || href == '' ) return false;

    $.ajax({
        type: "POST",
        async: true,
        url: href,
        cache: false,
        dataType: "json",
        success: function(data) {

            $("#content .contentwrap .itemwrap").html( data.content );
            init_submission_functions();
        }
    });

    return false;
});

$(".authorForm").unbind("submit").bind("submit", function() {

    var href = $(this).attr("action");
    if( href == null || href == '' ) return false;

    var affiliation = "blabla";

    $.ajax({
        type: "POST",
        async: true,
        url: href,
        affiliation: affiliation,
        cache: false,
        dataType: "json",
        success: function(data) {

            $("#content .contentwrap .itemwrap").html( data.content );
            init_submission_functions();
        }
    });

    return false;
});
}  

但是我仍然遇到相同的错误.

But I am still getting the same error.

推荐答案

使用 serialize发送序列化表格jQuery方法:

Send a serialized form using the serialize jQuery method:

$form.submit(function (e) {
    e.preventDefault();

    $this = $(this);
    $.post($this.attr('action'), $this.serialize(), function (response) {
        // handle the response here
    });
});

通过这种方式,Symfony将把提交请求作为普通请求处理-您无需做任何特殊的事情即可处理Ajax表单提交.您所需要做的就是返回 JsonResponse —当然,如果需要的话.

This way Symfony will handle the submit request as a normal request — you don't have to do anything special to handle an Ajax form submission. All you'll need to do is to return a JsonResponse — if you need it, of course.

以下是处理表格的示例-使其适应您的需求:

Here is an example of handling the form — adapt it to your needs:

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

    if ($form->isValid()) {
        // do something here — like persisting or updating an entity

        return new JsonResponse([
            'success' => true,
        ]);
    }

    return new JsonResponse([
        'success' => false,
        'form' => $this->render($pathToTheTemplateHere, [
            'form' => $form,
        ],
    ]);
}

另一种方法是使用不同的模板:form.json.twigform.html.twig-阅读文档以获取详细信息.

The other way would be to use different templates: form.json.twig and form.html.twig — read the docs for details.

这篇关于Symfony2:CSRF令牌无效.请尝试重新提交表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆