我需要在我的symfony項目中存儲一些map參數,爲此我需要在我的視圖中實現一些Ajax,這將能夠將一些信息傳遞給控制器。如何使用Symfony和Jquery創建POST 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
它確實存在,並返回「這不是阿賈克斯預期。但是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'或根本沒有輸出? – Touki
我什麼也沒有,我的控制檯... – Xavier
這很可能是由於PHP中的'FATAL'錯誤。嘗試直接在瀏覽器中輸入ajax請求地址(我知道,它不是'POST')並查看是否有一些Symfony錯誤... –