对控制器的简单 AJAX 请求 - Symfony3
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42221356/
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
Simple AJAX request to controller - Symfony3
提问by chicken burger
I use Symfony3 with PhpStorm.2016.3.2 on Ubuntu16.04
我在 Ubuntu16.04 上使用 Symfony3 和 PhpStorm.2016.3.2
I never done an AJAX request before and would like to test a call to controller from a view->to the controller->that sends an answer back to the view in JSON.
我以前从未执行过 AJAX 请求,并且想测试从视图到控制器的调用 -> 到控制器 -> 以 JSON 格式将响应发送回视图。
So I read on the doc but they are all very specific. So my desire is to only being able to write a simple AJAX request in a view(index.html.twig),for testing it, make a call to the controller(MainController.php)and return the answer in JSONin the view.
所以我阅读了文档,但它们都非常具体。所以我的愿望是只能在视图中编写一个简单的 AJAX 请求(index.html.twig),为了测试它,调用控制器(MainController.php)并JSON在视图中返回答案。
This is my view:
这是我的观点:
{% extends 'app/layout.html.twig' %}
{% block content %}
{% endblock %}
My controller:
我的控制器:
class MainController extends Controller
{
public function indexAction()
{
return $this->render('app/main/index.html.twig');
}
}
I really don't want to make the job done by the others, I just want to get a hint of how to make it work. So I'm sorry if my ticket is rather empty but maybe it can help others too, like me, to know where to start off.
我真的不想让其他人完成这项工作,我只是想知道如何让它发挥作用。所以如果我的票空了,我很抱歉,但也许它也可以帮助其他人,比如我,知道从哪里开始。
回答by Rawburner
At first you need to register the route to your controller:
首先,您需要将路由注册到控制器:
app_bundle_route:
path: /ajax_request
defaults: { _controller: AppBundle:Main:index }
Then load jQuery in your main view, perhaps you've done it already. You need a call to action in your template, some trigger to beginn the AJAX request:
然后在您的主视图中加载 jQuery,也许您已经完成了。您需要在模板中调用操作,一些触发器来开始 AJAX 请求:
{% extends 'app/layout.html.twig' %}
{% block content %}
<button class="ajax">click me!</button>
<div id="ajax-results">here comes the result</div>
<script>
$(document).on('click', 'button.ajax', function(){
that = $(this);
$.ajax({
url:'{{ (path('app_bundle_route')) }}',
type: "POST",
dataType: "json",
data: {
"some_var_name": "some_var_value"
},
async: true,
success: function (data)
{
console.log(data)
$('div#ajax-results').html(data.output);
}
});
return false;
});
</script>
{% endblock %}
And at least your controller is very simple:
至少你的控制器非常简单:
public function indexAction(Request $request)
{
if($request->request->get('some_var_name')){
//make something curious, get some unbelieveable data
$arrData = ['output' => 'here the result which will appear in div'];
return new JsonResponse($arrData);
}
return $this->render('app/main/index.html.twig');
}
I think this concept should make clear how it can work
我认为这个概念应该清楚它是如何工作的

