我需要在我的 symfony 项目中存储一些 map 参数,为此我需要在我的 View 中实现一些 Ajax,这将能够将一些信息传递给 Controller 。
我阅读了文档,尝试编写一些代码,但我无法让它工作。而且 Ajax 调试起来真的很痛苦。 这是 Controller 部分:
/**
* @Route("/ajax", name="_recherche_ajax")
*/
public function ajaxAction()
{
$isAjax = $this->get('Request')->isXMLHttpRequest();
if ($isAjax) {
return new Response('This is ajax response');
}
return new Response('This is not ajax!', 400);
}
和 JS :
map.on('zoomend', function(e) {
// use callback e variable
console.log('zoom: ' + e.target.getZoom());
$.ajax({
type: "POST",
url: "/recherche/ajax",
data: {
zoom: e.target.getZoom()
},
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
我检查了它确实存在的 url recherche/ajax
并按预期返回“这不是 Ajax”。但是 console.log 没有返回任何值...
这样做正确吗?
编辑: 看起来 Controller 无法处理 POST 请求。我试图将注释修改为:
/**
* @Route("/ajax", name="_recherche_ajax")
* @Method({"GET", "POST"})
*/
但它返回:
([Semantical Error] The annotation "@Method" in method MySite\SiteBundle\Controller\RechercheController::ajaxAction() was never imported. Did you maybe forget to add a "use" statement for this annotation?)
最佳答案
试试这个,
/**
* @Route("/ajax", name="_recherche_ajax")
*/
public function ajaxAction(Request $request)
{
if ($request->isXMLHttpRequest()) {
return new JsonResponse(array('data' => 'this is a json response'));
}
return new Response('This is not ajax!', 400);
}
在发送 Ajax 请求的情况下,您需要返回 json/plaintext/xml
数据,而不是整个 Response
对象。
PS:不要忘记为 Request
和 JsonResponse
添加 use 语句
编辑:正如您添加的错误消息所说,您需要使用导入注释 @Method
:
使用 Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
关于javascript - 如何使用 Symfony 和 Jquery 发出 POST Ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19375349/