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

标签 javascript php jquery ajax symfony

我需要在我的 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:不要忘记为 RequestJsonResponse 添加 use 语句

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

使用 Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

关于javascript - 如何使用 Symfony 和 Jquery 发出 POST Ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19375349/

相关文章:

javascript - 是否可以在 css 或 javascript 中在最后一行(或作为边框)添加一系列点

javascript - 动态更改文本颜色 AngularJS

javascript - 通过 Javascript、Jquery 或 Ajax 插入 XML 文件

javascript - 以 PDF 格式下载图表和表格

javascript - 在没有 MFC 的情况下从 C++ 运行 JavaScript 函数

javascript - 如何隐藏angularjs中的内容?

PHP 单元,使用单元测试测试 laravel 日志消息

php - Facebook 连接 : Error when clicking the Facebook Connect button

php - 如何使用 PHP 连接到 SQLite3 数据库

javascript - 如何调整我的 iframe