gpt4 book ai didi

ajax - 通过 Ajax 显示表单

转载 作者:行者123 更新时间:2023-12-05 00:44:42 25 4
gpt4 key购买 nike

编辑

SO 上的许多问题都是关于通过 Ajax 提交表单(this one 非常流行),而不是关于如何通过 ajax 调用显示表单。

我的问题是关于粗体部分:用户请求表单 -> ajaxCall -> displayForm -> 用户提交表单 -> 将表单发送到 Controller -> 验证表单 -> 向用户发送响应(错误与否)。


问题

作为 POST 的 ajax 调用,$request->isMethod('POST') 在执行 ajax 调用时总是返回 true。因此,如果通过 ajax 调用请求新表单,它将始终被验证。我附上了下面的代码,表格显示正常,但表格中显示以下错误消息:

The CSRF token is invalid.

问题是在 ajax 调用请求 Controller 中的表单期间正在验证表单。

附带说明一下,提交表单效果很好,验证效果也很好。

有谁知道如何在不验证空白新表单的情况下通过 Ajax 显示表单?

到目前为止我的代码:

/**
* Display the message as well as the form to reply to that message
*
* @param Request $request
* @return Response
*/
public function viewMessageAction(Request $request)
{
//Forbid every request but jQuery's XHR
if (!$request->isXmlHttpRequest()){
return new Response('', 200, array('Content-Type' => 'application/json'));
}

//Retrieve the message from the request
$messageId = $request->request->get('messageId');
$message = $this->getMessageManager->getMessage($messageId);

//Creates the form to reply to the message
$form = $this->container->get('reply_form.factory')->create($message);

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

if ($form->isValid()) {
//...
return $this->redirect($this->generateUrl('task_success'));
}
}

$answer =$this->container->get('templating')->renderResponse('AcmeMessageBundle:Message:message.html.twig', array(
'form' => $form->createView(),
'message' => $message
));

$response = new Response();
$response->headers->set('Content-type', 'application/json; charset=utf-8');
$response->setContent(json_encode($answer));
return $response;

}

编辑:jQuery 部分:

<script type="text/javascript">
$(function(){

var myPath = ;//...

function getMessage(messageId){
$.ajax({
type: "POST",
url: myPath,
data: "messageId="+messageId,
success: function(returnData){
$('#message').html(returnData);
}
});
}

});
</script>

最佳答案

ajax 调用并不总是需要 POST。它可以是 GET、PUT 或 DELETE。因此,当您进行 ajax 调用以获取表单时,请将其设为 GET 请求。

如果你正在使用 jquery,这里是你如何做的

$.ajax({
url: "http://localhost/proj/url",
type:'GET'
})

如果使用的是Using XHR,可以​​在open函数中指定类型

xhr.open( 'GET', URL)

PS:最好使用 JMS Serializer Service用于序列化而不是 json_encode

关于ajax - 通过 Ajax 显示表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15353539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com