【问题标题】:Symfony2 and Submit wit JavaScript: How to get html contentSymfony2 和提交机智 JavaScript:如何获取 html 内容
【发布时间】:2012-11-02 07:53:03
【问题描述】:

我在 Symfony2 项目中有一个表单,我需要提交表单。第一个想法是使用 ajax 提交,但问题是这不会通过 symfony2 所需的验证,并且我收到 CSRF 错误消息(请参阅我的先前问题:Symfony2: The CSRF token is invalid. Please try to resubmit the form)。

感谢@Elnur 的回答,我现在可以使用 $post 提交表单,但还有另一个问题。

通过 Ajay,我得到了一个 html 响应,并且我能够将此响应分配给一个 HTML 元素:

$.ajax({
    type: "POST",
    async: true,
    url: href,
    cache: false,
    dataType: "json",
    success: function(data) {
        $("#content .contentwrap .itemwrap").html( data.content );
    }
});

这是我得到的回复:

<div class="item item-last">
<h1>Create Affiliation</h1>
        <div class="error">
        <ul><li>The CSRF token is invalid. Please try to resubmit the form</li></ul>
        <ul><li>The Affiliation should not be blank</li></ul>

    </div>

</div>
<div class="item item-last">
<form action="/app_dev.php/user/submission/affiliation/create/4a0ad9f8020c5cd5712ff4c4c8921b32?ajax=no" method="POST" class="authorForm" >
    <div style="float:left;">
        <table width="100%" cellspacing="0" cellpadding="0">
            <tr>
                <td>
                    <label for="submissionAffiliationForm_affiliation" class=" required">Affiliation</label>
                </td>
                <td>
                    <input type="text" id="submissionAffiliationForm_affiliation" name="submissionAffiliationForm[affiliation]" required="required"    size="40" />
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;
                </td>
                <td>
                    <div class="button button-left button-cancel">
                        <img src="/bundles/sciforumversion2/images/design/new/button-red.png"/>
                        <a href="/app_dev.php/user/submission/author/edit/4a0ad9f8020c5cd5712ff4c4c8921b32/0" class="submission_link">cancel</a>
                    </div>
                    <div style="float: left;">&nbsp;</div>
                    <div class="button button-left button-cancel">
                        <img src="/bundles/sciforumversion2/images/design/new/button.png"/>
                        <input type="submit" name="login" value="submit" />
                    </div>
                    <div style="clear: both;"></div>
                </td>
            </tr>
        </table>
    </div>

    <input type="hidden" id="submissionAffiliationForm__token" name="submissionAffiliationForm[_token]" value="de9690f61f0ee5f30fdcc5152f44e76787f34bbb" />

</form>
</div>

但是现在,当使用 post 时:

$.post($this.attr('action'), $this.serialize(), function (data) {
    $("#content .contentwrap .itemwrap").html( data );
});

我不再收到 HTML 而是 JSON 格式的响应,我不知道如何从中提取正确的信息。

这是我从帖子中得到的回复:

{"responseCode":400,"errors":false,"submitted":false,"content":"<!DOCTYPE html>\n<html>\n    <head>\n        <meta http-equiv=\"Content-Type\" content=\"text\/html; charset=utf-8\" \/>\n        <meta http-equiv=\"refresh\" content=\"1;url=\/app_dev.php\/user\/submission\/4a0ad9f8020c5cd5712ff4c4c8921b32\" \/>\n\n        <title>Redirecting to \/app_dev.php\/user\/submission\/4a0ad9f8020c5cd5712ff4c4c8921b32<\/title>\n    <\/head>\n    <body>\n        Redirecting to <a href=\"\/app_dev.php\/user\/submission\/4a0ad9f8020c5cd5712ff4c4c8921b32\">\/app_dev.php\/user\/submission\/4a0ad9f8020c5cd5712ff4c4c8921b32<\/a>.\n    <\/body>\n<\/html>","notice":""}

这是控制器的样子:

$em         = $this->getDoctrine()->getEntityManager();
    // get the user object
    $user       = $this->get('security.context')->getToken()->getUser();
    $submission = $em->getRepository('SciForumVersion2Bundle:Submission')->findOneBy( array("hash_key"=>$hash_key) );
    $author     = $em->getRepository('SciForumVersion2Bundle:SubmissionAuthor')->findOneBy( array("id"=>$author_id, "hash_key"=>$hash_key) );
    if( $author == null ) {
        $author = new SubmissionAuthor();
        $author->setPerson( new Person() );
    }

    $enquiry    = new Affiliation();
    $formType   = new SubmissionAffiliationFormType();
    $form       = $this->createForm($formType, $enquiry);

    $request    = $this->getRequest();
    $valid      = true;
    $error      = '';
    if( $request->get('cancel') == 'yes' ) return $this->redirect($this->generateUrl('SciForumVersion2Bundle_user_submission', array("key"=>$submission->getHashKey())));
    if ($request->getMethod() == 'POST' && $request->get('ajax') == 'no') {

        $form->bindRequest($request);

        if ($valid = $form->isValid()) {

            if( $valid ) {

                $em->persist($enquiry);
                $em->flush();

                $uAff = new UserAffiliation();
                $uAff->setUserId( $user->getId() );
                $uAff->setAffiliationId( $enquiry->getId() );
                $uAff->setUser( $user );
                $uAff->setAffiliation( $enquiry );
                $em->persist($uAff);
                $em->flush();

                // Redirect - This is important to prevent users re-posting
                // the form if they refresh the page
                return $this->redirect($this->generateUrl('SciForumVersion2Bundle_user_submission', array("key"=>$submission->getHashKey())));
            }
        }

【问题讨论】:

  • 你能告诉我们你的控制器吗?
  • @Touki,谢谢。我会在一分钟内更新我的问题。
  • 您的 AJAX 请求需要返回。 Symfony 正在尝试重定向用户。您不能从 AJAX 请求重定向。如果您想显示内容,请执行此操作。 $("#content .contentwrap .itemwrap").html( data.content );
  • 是的。这将使用 Symfony 重定向填充您的“.itemwrap”。

标签: php javascript json post symfony


【解决方案1】:

您的问题是您正在返回一个全新的 HTML 内容。
您只需要返回您的 JS 可以理解的信息并按照您想要的方式对待。

use Symfony\Component\HttpFoundation\Response;

SF 中的此类允许您返回纯内容。

这是一种使用方法。

if ($valid) {
    $data = array(
        'success' => true,
        'responseCode' => 307, /* Redirect Temp */
        'redirectURI' => $this->generateUrl('SciForumVersion2Bundle_user_submission', array("key"=>$submission->getHashKey())),
        'message' => '<h3>You\'re about to be redirected...</h3>'
    );
} else {
    $data = array(
        'success' => false,
        'responseCode' => 400, /* Bad Request */
        'message' => '<h3 class="error">Cannot send form<br>* Field NAME is empty</h3>'
    );
}
$json = json_encode($data);
/* Response($data,$statusCode,$additionnalHeaders) */
return new Response($json,200,array('Content-Type'=>'application/json'));

然后在你的 JS 中

$.ajax({
    url: "uri/to/controller",
    type: "POST",
    data: values, /* Sent data */
    cache: false,
    success : function(data,e,xhr){
        if (xhr.status == 200) {
            if (data.responseCode == 200) { /* Success, just a message */
                $("#content .contentwrap .itemwrap")
                    .addClass("success")
                    .html(data.message);
            } else if (data.responseCode == 307) { /* Redirection */
                $("#content .contentwrap .itemwrap")
                    .addClass("success")
                    .html(data.message);
                setTimeout(function(){
                    $(window).attr("location",data.redirectURI);
                },3000);
            } else if (data.responseCode == 400) { /* Invalid Form */
                $("#content .contentwrap .itemwrap")
                    .addClass("error")
                    .html(data.message);
            } else { /* Could not understand Response Code */
                $("#content .contentwrap .itemwrap")
                    .html("<h3>Technical issue occured. Please come back later.</h3>");
            }
        } else {
            $("#content .contentwrap .itemwrap")
                .html("<h3>Technical issue occured. Please come back later.</h3>");
        }
    }
})

你可以想象任何参数要通过$data

我使用 HTTP/1.1 代码与 Javascript 交谈,但你可以使用任何你想要的
例如:

'action' => 'redirect'
'youAreGoingTo' => 'printAwesomeMessage'

JS

if (data.action == 'redirect')

if (data.youAreGoingTo == 'printAwesomeMessage')

【讨论】:

  • 很好的答案和很好的帮助,一个真正的专业人士。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2011-11-20
  • 2013-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 2015-09-02
相关资源
最近更新 更多