我在 Ubuntu16.04 上使用 Symfony3 和 PhpStorm.2016.3.2
我以前从未执行过 AJAX 请求,并且想测试从 View 到 Controller 的调用-> 到 Controller -> 以 JSON 格式将响应发送回 View 。
所以我阅读了文档,但它们都非常具体。所以我的愿望是只能在 View 中编写一个简单的 AJAX 请求 (index.html.twig)
,为了测试它,调用 Controller (MainController.php)
并在 JSON
中返回答案在 View 中。
这是我的观点:
{% extends 'app/layout.html.twig' %}
{% block content %}
{% endblock %}
我的 Controller :
class MainController extends Controller
{
public function indexAction()
{
return $this->render('app/main/index.html.twig');
}
}
我真的不想让其他人完成这项工作,我只是想知道如何让它发挥作用。所以如果我的票是空的,我很抱歉,但也许它也可以帮助其他人,比如我,知道从哪里开始。
最佳答案
首先,您需要将路由注册到 Controller :
app_bundle_route:
path: /ajax_request
defaults: { _controller: AppBundle:Main:index }
然后在您的主 View 中加载 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 %}
至少你的 Controller 非常简单: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');
}
我认为这个概念应该清楚它是如何工作的
关于ajax - 对 Controller 的简单 AJAX 请求 - Symfony3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42221356/