简体   繁体   English

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

[英]How to make a POST Ajax request with Symfony and Jquery

I need to store some map parameter in my symfony project, to do this i need to implement some Ajax in my view which will be able to pass some info to the controller. 我需要在我的symfony项目中存储一些map参数,为此我需要在我的视图中实现一些Ajax,它将能够将一些信息传递给控制器​​。

I read the docs, try to write some code but i can't make it works. 我阅读了文档,尝试编写一些代码,但我无法使其工作。 And Ajax is really painfull to debug. 而Ajax真的很难调试。 Here is the controller part : 这是控制器部分:

 /**                                                                                   
 * @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);
}

And the JS : 和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);
        }
    });

});

I check the url recherche/ajax it does exist and return the 'This is not Ajax' as expected. 我检查它确实存在的url recherche/ajax并按预期返回'This is not Ajax'。 But the console.log does not return any value... 但是console.log没有返回任何值......

Is that the right way to do this ? 这是正确的方法吗?

EDIT : It looks like the controller can't handle POST Request. 编辑:看起来控制器无法处理POST请求。 I tried to modify the annotations to : 我试图将注释修改为:

 /**                                                                                   
 * @Route("/ajax", name="_recherche_ajax")
 * @Method({"GET", "POST"})
 */

But it returns : 但它返回:

([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?) 

Try this, 试试这个,

/**                                                                                   
 * @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);
}

In case of you sending an Ajax request, you need to return json/plaintext/xml data, and not a whole Response object. 如果发送Ajax请求,则需要返回json/plaintext/xml数据,而不是整个Response对象。

PS: Do not forget to add use statment for Request and JsonResponse PS:不要忘记为RequestJsonResponse添加use statment

EDIT : As the error message you added says, you need to import the annotation @Method by using : 编辑:正如您添加的错误消息所示,您需要使用以下命令导入注释@Method

use Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Method;

I was looking the entire internet and didn't find any solution to similar problem. 我正在寻找整个互联网,并没有找到任何类似问题的解决方案。 But i found it-> I had neither issue with the controller, nor the javascript/jquery/ajax nor the security issues. 但我发现它 - >我既没有控制器问题,也没有javascript / jquery / ajax问题,也没有安全问题。 It was in .... wait for it.... in HTML. 它在...等待它....在HTML中。 i had to add type="button" into html tag, otherwise whole page was refreshing. 我不得不在html标签中添加type =“button”,否则整个页面都在刷新。 4 hours wasted on debugging purposes.. but lessons learned. 在调试目的上浪费了4个小时..但是经验教训。

How to debug problems? 如何调试问题? 1. Check if ajax is sending post and matching post route on the client side. 1.检查ajax是否在客户端发送帖子和匹配的帖子路由。 Firefox -> f12 -> network -> watch the POST events 2. Check the symfony profiler (very usefull tool!) on the -> /app_dev.php/ (dev enviroment) -> Get Request/Response submenu end take last 10, if You see the POST route check closely if its return code and parameters (you wont see response, if its set other than HTML response) 3. In your controller do some action that can be checked if the script inside this route was executed. Firefox - > f12 - >网络 - >观看POST事件2.检查symfony profiler(非常有用的工具!) - > /app_dev.php/(开发环境) - >获取请求/响应子菜单结束最后10个,如果您看到POST路由密切检查其返回代码和参数(您不会看到响应,如果其设置不是HTML响应)3。在您的控制器中执行一些操作,如果此路由中的脚本已执行,则可以检查该操作。 If so, and You see no response its either on the server side (controller) or client side (twig/ajax/html) 4. Code examples: 如果是这样,并且您在服务器端(控制器)或客户端(twig / ajax / html)看到没有响应.4。代码示例:

Button in html (this was my issue) html中的按钮(这是我的问题)

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

Ajax in html or other included js file: 在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");
    }

Now.. server side. 现在..服务器端。 Controller: 控制器:

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 create new file in web directory. File put contents在Web目录中创建新文件。 If it was matched and file is created that means, that You matched the route, but didn't get the response 如果它匹配并且创建了文件意味着,您匹配路线,但没有得到响应

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM