php - Symfony2 : The CSRF token is invalid. 请尝试重新提交表单

标签 php symfony csrf

我有一个表格,我必须在其中填写一些信息。 即使我在里面放了东西,我也会收到错误:

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

与此问题相关:symfony2 CSRF invalid我正确使用了 $form->bindRequest()

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

这是我的模板( Twig )代码:

<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;
});
}  

但我仍然遇到同样的错误。

最佳答案

使用 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 — 当然,如果您需要的话。

这是处理表单的示例——根据您的需要进行调整:

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 — 阅读文档了解详情。

关于php - Symfony2 : The CSRF token is invalid. 请尝试重新提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13154035/

相关文章:

php - 从另一个表中选择一列用作选择键后,Mysql 连接四个表

php - 即使从数据库中获取值后,在 codeigniter 3 中获取 undefined index 返回日期?

php - Symfony 3.3 内置服务器错误

forms - 如何在表单中仅加载 OneToMany 关联的子集?

ruby-on-rails - 如何在 Rails 中处理带有陈旧 CSRF 真实性 token 的页面

php - 处理丢失的数组偏移量

PHP 将日期格式插入输入的 "placeholder"

php - Doctrine 2.1 性能问题

Laravel X-CSRF-Token 与 POSTMAN 不匹配

java - 使用 Spring RestTemplate 请求 XSRF-TOKEN 时出现异常