我在Ubuntu16.04上使用Symfony3和PhpStorm.2016.3.2
我之前从未做过AJAX请求,并且想要从view->到controller->测试对控制器的调用,该调用将回答发送回JSON中的视图.
所以我读了文档,但它们都非常具体.所以我的愿望是只能在视图中编写一个简单的AJAX请求(index.html.twig),进行测试,调用控制器(MainController.php)并JSON在视图中返回答案.
这是我的看法:
{% extends 'app/layout.html.twig' %}
{% block content %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
我的控制器:
class MainController extends Controller
{
public function indexAction()
{
return $this->render('app/main/index.html.twig');
}
}
Run Code Online (Sandbox Code Playgroud)
我真的不想让其他人完成这项工作,我只是想知道如何让它工作.所以我很抱歉,如果我的机票很空,但也许它可以帮助其他人,比如我,知道从哪里开始.
Raw*_*ner 28
首先,您需要注册到控制器的路由:
app_bundle_route:
path: /ajax_request
defaults: { _controller: AppBundle:Main:index }
Run Code Online (Sandbox Code Playgroud)
然后在主视图中加载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 %}
Run Code Online (Sandbox Code Playgroud)
至少你的控制器非常简单:
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');
}
Run Code Online (Sandbox Code Playgroud)
我认为这个概念应该明确它是如何工作的
| 归档时间: |
|
| 查看次数: |
27446 次 |
| 最近记录: |