在我的symfony(v3.4)项目中,我需要将一些javascript变量从视图传递到控制器:我正在使用Jquery和Ajax将变量发送到控制器,但是我无法访问变量。 我的Ajax请求没有问题,我通过Symfony探查器进行了检查,请求已正确发送,但是由于某种原因,控制器甚至无法检测到Ajax请求。
这是我的控制人:
public function saisieAction(Request $request)
{
$user = $this->getUser();
$thisyear = date("Y");
$em = $this->getDoctrine()->getManager();
// Create the form
$form = $this->get('form.factory')->createBuilder(FormType::class)
->add('ndf', CollectionType::class, array(
'entry_type' => NoteDeFraisType::class,
'label' => false,
'allow_add' => true,
'allow_delete' => true,
))
->getForm();
// if the form has been submited
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
if($request->isXMLHttpRequest()){
//After some code debuging, this is never
//executed
$month = $request->get('month');
$year = $request->get('year');
$sub_date = $month .'/' .$year;
}
$notesDeFrais = $form['ndf']->getData();
foreach ($notesDeFrais as $ndf) {
$ndf->setUser($user);
$ndf->setMonth($sub_date);
$em->persist($ndf);
}
$em->flush();
}
return $this->render('AvPlatformBundle:Platform:saisie.html.twig',
array(
'year' => $thisyear, 'form' => $form->createView()
));
}
还有saisie.html.twig视图中的脚本:
$(".month").click(function() {
var click = $(this);
var month = click.val();
var year = $("#years").val();
$.post("{{ path('avaliance_platform_saisie') }}",
{ 'month' : month,
'year' : year
},
function (data,status) {
alert('Data sent');
});
});
答案 0 :(得分:0)
我真的不明白这里的服务器语言是什么,但是我认为在您的发帖请求中您丢失了。 contentType(您要发送到服务器的数据类型)和dataType(您希望从服务器返回的数据类型)
contentType:“ application / json; charset = utf-8”, dataType:“ json”,
还要检查您的控制器操作方法是否已配置为接收发布http数据。
答案 1 :(得分:0)
从源代码开始:
/**
* Returns true if the request is a XMLHttpRequest.
*
* It works if your JavaScript library sets an X-Requested-With HTTP header.
* It is known to work with common JavaScript frameworks:
*
* @see http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
*
* @return bool true if the request is an XMLHttpRequest, false otherwise
*/
public function isXmlHttpRequest()
{
return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
}
因此,问题在于AJAX请求没有此标头。 JQuery应该自动将其放入,除非有理由将其排除在外。跨域请求就是这种原因之一。
可以手动插入标头(但仅用于调试):
$.post("{{ path('avaliance_platform_saisie') }}",
{ 'month' : month,
'year' : year
},
headers: {'X-Requested-With': 'XMLHttpRequest'},
function (data,status) {
alert('Data sent');
});
});