如何使用Symfony和Jquery发出POST Ajax请求

我需要在我的symfony项目中存储一些map参数,为此我需要在我的视图中实现一些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并按预期返回’This is not 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?) 

试试这个,

 /** * @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:不要忘记为RequestJsonResponse添加use statment

编辑:正如您添加的错误消息所示,您需要使用以下命令导入注释@Method

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

我正在寻找整个互联网,并没有找到任何类似问题的解决方案。 但我发现它 – >我既没有控制器问题,也没有javascript / jquery / ajax问题,也没有安全问题。 它在…等待它….在HTML中。 我不得不在html标签中添加type =“button”,否则整个页面都会令人耳目一新。 在调试目的上浪费了4个小时..但是经验教训。

如何调试问题? 1.检查ajax是否在客户端发送post和匹配的post路由。 Firefox – > f12 – >网络 – >观看POST事件2.检查symfony profiler(非常有用的工具!) – > /app_dev.php/(开发环境) – >获取请求/响应子菜单结束最后10个,如果您看到POST路由密切检查其返回代码和参数(您不会看到响应,如果其设置不是HTML响应)3。在您的控制器中执行一些操作,如果此路由中的脚本已执行,则可以检查。 如果是这样,你在服务器端(控制器)或客户端(twig / ajax / html)看到没有响应.4。代码示例:

html中的按钮(这是我的问题)

  

在HTML或其他包含的js文件中的Ajax:

 function aButtonPressed(){ $.post('{{path('app_tags_sendresponse')}}', {data1: 'mydata1', data2:'mydata2'}, function(response){ if(response.code === 200 && response.success){ alert('success!'); } else{ alert('something broken'); } }, "json"); } 

现在..服务器端。 控制器:

 namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; class JsonApiController extends Controller /** * @Route("/api/programmers") * @Method("POST") */ public function sendResponse() { if(isset($_POST['data1'])){ $json = json_encode(array('data' => $_POST['data1']), JSON_UNESCAPED_UNICODE); file_put_contents("test.json", $json); return new JsonResponse($json); } return new Response('didn't set the data1 var.'); } } 

File put contents在Web目录中创建新文件。 如果匹配并且创建了文件意味着您匹配路由,但没有得到响应