gpt4 book ai didi

javascript - 交响乐团 3/4 : delete a table row from a database through AJAX

转载 作者:行者123 更新时间:2023-12-01 01:35:23 25 4
gpt4 key购买 nike

我的 Symfony 代码有点卡住了。

让我解释一下

我的数据库中有一个待办事项列表表,其中包含:

  • ID 名为:id
  • 名为:todo 的名称字段
  • 还有其他 3 个无关紧要的字段:“completed”、“created_at”、“updated_at”
<小时/>

在进一步之前:这是我的代码

相关控制者:

  /**
* @Route("/todos/delete/{id}", name="todo.delete", methods={"POST"})
* @param Todo $todo
* @param ObjectManager $manager
* @param Request $request
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function delete(Todo $todo, ObjectManager $manager, Request $request)
{
$manager->remove($todo);
$manager->flush();

if ( $request->isXmlHttpRequest()) {
return $this->redirectToRoute('todo.home', [
'id' => $todo->getId()
]);
}
throw $this->createNotFoundException('The todo couldn\'t be deleted');
}

View :

{% extends 'base.html.twig' %}

{% block title %}Todos{% endblock %}

{% block content %}
<br>
<form action="{{ path('todo.create') }}" method="post">
<input type="hidden" name="token" value="{{ csrf_token('todo-create') }}"/>
<label for="todo">Todo</label>
<input type="text" id="todo" name="todo" class="form-control input-group-lg" placeholder="Create a new todo">
</form><br>
{% for todo in todos %}
{{ todo.todo }}
<a href="{{ path('todo.update', {'id': todo.id}) }}" class="btn btn-info btn-sm">Update</a>
<a href="{{ path('todo.delete', {'id': todo.id}) }}" class="btn btn-danger btn-sm js-delete-todo" id="{{ todo.id }}">x</a>
{% if todo.completed %}
<a href="{{ path('todo.completed', {'id': todo.id}) }}" class="btn btn-success btn-sm">Completed !</a>
{% else %}
<a href="{{ path('todo.completed', {'id': todo.id}) }}" class="btn btn-warning btn-sm">Mark as completed</a>
{% endif %}
<hr>
{% endfor %}
{% endblock %}

我们关注:

<a href="{{ path('todo.delete', {'id': todo.id}) }}" class="btn btn-danger btn-sm js-delete-todo" id="{{ todo.id }}">x</a>

JavaScript:

$(document).ready(function () {
$('.js-delete-todo').on('click', function (e) {
e.preventDefault();

var url = $(this).attr('href');
delTodo(url);

function delTodo(url) {
$.ajax({
type: "POST",
url: url
}).done(function (data) {
$('#id').remove();
}).fail(function () {
alert('Could not be deleted');
});
}
});
});

实际上

一切似乎都正常:它执行POST ajax 请求,并删除数据库表中的行。

唯一的问题是我必须按 F5 才能看到它。

如何在不重新加载页面或按 F5 热键的情况下使其工作?

最佳答案

在您的 symfony 代码中,您应该返回 JSON 格式,例如 here 。像这样将您的待办事项包装在容器中

{% for todo in todos %}
<div id="todo-{{todo.id}}">
// your todo staff here
</div>
{% endfor %}

然后将您的 JavaScript 更改为

function delTodo(url) {
$.ajax({
type: "POST",
url: url
}).done(function (data) {
var id = JSON.parse(data).id;
$('#todo-' + id).remove();
}).fail(function ()
alert('Could not be deleted');
});
}

关于javascript - 交响乐团 3/4 : delete a table row from a database through AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52878420/

25 4 0