我试图在单击按钮后使用AJAX运行我的控制器代码。从我收集的信息来看,这就是您应该使用AJAX的原因......它会从前端向后端发送响应,然后生成json响应。如何在Symfony2中正确使用AJAX
但我无法弄清楚如何正确地做到这一点。我不确定如何让AJAX成功运行控制器代码。
所有我已经能够做的就是展示在成功的表,但我不希望控制器代码运行按钮被点击,直到,因为这是AJAX的点。
的Symfony似乎并不对此有文档:http://symfony.com/legacy/doc/book/1_0/en/11-Ajax-Integration
而且这些堆栈溢出的问题/答案是太老了我的使用或不帮我:
How to integrate Ajax with Symfony2
How to make a POST Ajax request with Symfony and Jquery
嫩枝:
<button id="begin-check" type="button">Run Test</button>
<table class="stab">
<thead>
<tr>
<th style="text-align: center">Ang</th>
<th style="text-align: center">Lat</th>
</tr>
<tr>
<th>Name & Age</th>
<th>Name & Age</th>
</tr>
</thead>
<tbody>
{% for person in persons %}
<tr>
<td>
<a href="{{ path('users_edit', { 'id': person[0] }) }}">
{{ person[1] }}, {{ person[2] }}
</a>
</td>
<td>
{% if person[7] == 'Moe' %}
<a href="{{ path('edit', { 'id': person[6] }) }}">
{% else %}
<a href="{{ path('low_edit', { 'id': person[8] }) }}">
{% endif %}
{{ person[4] }}, {{ person[5] }}
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
AJAX:
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', "#begin-check", function(e){
console.log('You have clicked');
e.preventDefault();
$.ajax({
method: 'POST',
url: "{{ path('control_check') }}",
data: { //research what to put here
},
success: function(responseData){
//run the controller code
//Show HTML table
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(xhr.responseText);
console.log(thrownError);
},
})
});
});
</script>
在控制器:
/**
*
* @Route("/control", name="control_check")
* @Template()
*/
public function controlCheckAction()
{
$request = $this->get('request');
$em = $this->getDoctrine()->getManager();
$persons = array();
//more code
return new JsonResponse(array('persons' => $persons));
}
是你的javascript代码插入树枝模板吗? –
它与上面的我的树枝在同一个文件中 – grgre
您不能在JavaScript成功函数中运行严重的侧控制器代码。当调用成功时,responseData将拥有controlCheckAction生成的任何json。然后您需要javascript来渲染表格。看看你是否能找到一个好的介绍Ajax教程,而没有Symfony的复杂性。你需要首先理解基础知识。 – Cerad