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

How to make a POST Ajax request with Symfony and Jquery

本文关键字:POST Ajax 请求 发出 Jquery 何使用 Symfony      更新时间:2023-09-26

我需要在我的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它确实存在,并按预期返回"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 的使用状态

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

use Sensio'Bundle'FrameworkExtraBundle'Configuration'Method;

我查看了整个互联网,没有找到类似问题的任何解决方案。但我找到了->我既没有控制器的问题,也没有javascript/jquery/ajax的问题,更没有安全问题。它在。。。。等待它……在HTML中。我不得不在html标签中添加type="button",否则整个页面都会刷新。为调试目的浪费了4个小时。。但要吸取教训。

如何调试问题?1.检查ajax是否在客户端发送post和匹配post路由。Firefox->f12->网络->观看POST事件2.检查->/app_dev.php/(dev-environment(->Get-Request/Response子菜单end take last 10上的symfony探查器(非常有用的工具!(,如果你看到POST路由,请仔细检查它的返回代码和参数(如果它的设置不是HTML响应,你就看不到响应(3.在控制器中执行一些操作,如果执行了该路由内的脚本,则可以检查这些操作。如果是这样,则在服务器端(控制器(或客户端(twick/ajax.html(都没有看到响应4.代码示例:

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

<button name="button" id="button" class="button" type="button" value="100"> Click me </button> 

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目录中创建新文件。如果匹配并创建了文件,则意味着您匹配了路由,但没有得到响应