我试图找出如何使用复选框启用/禁用用户而不重新加载页面。
index.html.twig
<table>
<thead>
<tr>
<th>UserName</th>
<th>Enabled</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<td><a href="{{ path('user_show', {'id': user.id}) }}">
{{ user.username }}</a>
</td>
<td><input id="user_enable_{{ user.id }}" onclick="enabledChange({{ user.id }})"
type="checkbox" {% if user.enabled %}checked{% endif %}/>
</td>
{% endfor %}
</tbody>
</table>
<script>
var changePath = {{ path('user_enable_change', {'id': user.id}) }};
function enabledChange(id)
{
var value = $(this).val();
console.log('value: ' + value);
$.ajax({
type: "POST",
url: changePath,
async: true,
data: { },
success: function () {
console.log('success');
}
});
}
</script>
UserController中
/**
* @Route("/enable/{id}", name="user_enable_change")
*/
public function userDisableAction(User $user) {
if($user->isEnabled()){
$user->setEnabled(false);
}else {
$user->setEnabled(true);
}
try {
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
}
catch(\Exception $e) {
return new JsonResponse('error');
}
return new JsonResponse('success');
}
问题
如何根据用户状态将相应的用户ID设置为enabledChange函数并更改检查状态?
答案 0 :(得分:1)
您需要在变量中添加引号,并将changePath
作为参数传递:
onclick="enabledChange('{{ user.id }}', '{{ path('user_enable_change', {'id': user.id}) }}')"
然后:
function enabledChange(id, changePath) {
var value = $(this).val();
console.log('value: ' + value);
$.ajax({
type: "POST",
url: changePath,
async: true,
data: { },
success: function () {
console.log('success');
}
});
}
我希望这会有所帮助。
答案 1 :(得分:0)
另一种干净的方法是通过数据属性传递参数和路由,并按类访问按钮。在我的示例中,我必须增加产品数量而不刷新:
input {
padding: 1em;
}
::-webkit-input-placeholder {
background: -webkit-linear-gradient(left, #AAA 0%, #AAA 70%,red 70%, red 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}