如何通过 symfony2 控制器获取 Ajax 发布请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18826821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 11:06:22  来源:igfitidea点击:

How to get Ajax post request by symfony2 Controller

ajaxsymfony

提问by whitebear

I send text message like this

我发送这样的短信

html markup

html标记

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

javascript code

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);
    }
});

symfony2 controller code

symfony2 控制器代码

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

but $textis null ...

$text为空...

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

我已经尝试过 firefox http 请求测试器的正常发布请求(不是 Ajax)。

/app_dev.php/member/msgPost

Controller works and $texthas a value.

控制器工作并$text具有价值。

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

所以我认为php代码是可以的,但是Ajax方面存在问题

'success:function' is called as if succeeded.

'success:function' 就像成功一样被调用。

How can you get the contents of javascript data structure?

如何获取javascript数据结构的内容?

回答by sf_tristanb

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

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

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

所以基本上你的代码应该是这样的 Controller.php

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

Also, make sure by the data you are sending is not null by using console.log(data)in the JS of your application.

此外,通过console.log(data)在应用程序的 JS 中使用,确保您发送的数据不为空。

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 requestvariable and you used a datavariable name in your controller.

最后是你的问题的答案:你没有使用正确的变量,你需要访问的值,$('#request').val()但你将它存储在一个request变量中,并且data在你的控制器中使用了一个变量名。

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

考虑更改变量的名称,因为它令人困惑。

回答by Elnur Abdurrakhimov

If you're sending the data as JSON — not as form urlencoded — you need to access the request body directly:

如果您以 JSON 格式发送数据——而不是 urlencoded 格式——则需要直接访问请求正文:

$data = json_decode($request->getContent());

回答by mangel.snc

You are doing it wrong when obtaining the value, you must use:

获取值时你做错了,你必须使用:

$data = $request->request->get('request');

'cause requestis the name of your parameter.

因为request是您的参数名称。