如何获得通过Symfony2的控制器的Ajax post请求 [英] How to get Ajax post request by symfony2 Controller

查看:1026
本文介绍了如何获得通过Symfony2的控制器的Ajax post请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发这样的短信

在HTML

<textarea id="request" cols="20" rows="4"></textarea>

在JavaScript

in javascript

        var data = {request : $('#request').val()};

        $.ajax({
            type: "POST",
            url: "{{ path('acme_member_msgPost') }}",
            data: data,
            success: function(data, dataType)
            {
                alert(data);
            },

            error: function(XMLHttpRequest, textStatus, errorThrown)
            {
                alert('Error : ' + errorThrown);
            }

我写了code在Symfony2中Contololler

I wrote the code in symfony2 Contololler

    $request = $this->container->get('request');
    $text = $request->request->get('data');

但$ text为null .....

but $text is null .....

我已经试过正常POST请求(不阿贾克斯)通过Firefox的HTTP请求测试。

I have tried normal post request(not Ajax) by firefox http request tester.

/app_dev.php/member/msgPost

/app_dev.php/member/msgPost

控制工程和$文本具有价值。

Controller works and $text has value.

所以,我认为PHP的code是好的,没有对阿贾克斯的一面,但是

So I think php code is OK, there is the problem on Ajax side,however

。成功:函数被称为如果成功

'success:function' is called as if succeeded.

你怎么能得到的JavaScript数据结构的内容?

How can you get the contents of javascript data structure?

推荐答案

首先,你并不需要访问容器控制器,因为它已经实现了 ContainerAware

First, you don't need to access the container in your controller as it already implements ContainerAware

所以基本上你的code应该是这样在你的 Controller.php这样

So basically your code should look like this in your Controller.php

public function ajaxAction(Request $request)
{
    $data = $request->request->get('request');
}

此外,还要确保你所发送的数据是不是在你的应用程序中的JS使用空的console.log(数据)

最后你的问题的答案:你没有使用正确的变量,你需要访问的 $('#要求)的值VAL() ,但你存储在一个要求变量,而您在使用了数据变量名的控制器。

And finally the answer of your question : you are not using the right variable, you need to access the value of $('#request').val() but you stored it in a request variable and you used a data variable name in your controller.

考虑更改变量的名称,因为它是混乱的。

Consider changing the name of the variable, because it's confusing.

这篇关于如何获得通过Symfony2的控制器的Ajax post请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆