【发布时间】:2017-06-09 08:45:18
【问题描述】:
单击按钮后,我正在尝试使用 AJAX 运行我的控制器代码。根据我收集到的信息,这就是您应该使用 AJAX 的目的……它从前端向后端发送响应,然后生成 json 响应。
但是我不知道如何正确地做到这一点。我不确定如何让 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 代码是在 twig 模板中吗?
-
它和我上面的树枝在同一个文件中
-
您不能从您的 javascript 成功函数内部运行服务器端控制器代码。调用成功时,您的 responseData 将具有 controlCheckAction 生成的任何 json。然后,您需要 javascript 来呈现表格。看看你是否能找到一个很好的 ajax 入门教程,而不用 Symfony 的复杂性。您需要先了解基础知识。
标签: javascript php jquery ajax symfony