【发布时间】:2013-10-22 21:51:28
【问题描述】:
我需要在我的 symfony 项目中存储一些地图参数,为此我需要在我的视图中实现一些 Ajax,以便能够将一些信息传递给控制器。
我阅读了文档,尝试编写一些代码,但我无法使其工作。而且 Ajax 调试起来真的很痛苦。 这是控制器部分:
/**
* @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 没有返回任何值...
这是正确的做法吗?
编辑: 看起来控制器无法处理 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?)
【问题讨论】:
-
是响应输出
undefined还是什么都没有输出? -
我的控制台一无所有...
-
这很可能是由于 PHP 中的
FATAL错误。尝试直接在浏览器中输入ajax请求地址(我知道,不是POST),看看是否有Symfony错误... -
@x_vi_r 在调试器中打开网络选项卡,处理 Ajax 请求并检查浏览器给出的响应。检查是否触发了事件,如果是,请查看是否返回了
500StatusCode。如果是这样,您可以验证您的app/logs文件夹中发生了什么。 -
然后在文件顶部添加
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
标签: javascript php jquery ajax symfony