javascript 使用 JQuery 删除数据库行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20754465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete a database row using JQuery
提问by Fawzan
I am using a PHP function to format any 2D PHP array to HTML table, In that table I need to add a delete button in each row, So when the user clicks the delete button jQuery should take particular fields ( 3 fields ) and submit in a php file and it should give the response without reloading the page, I have several dynamic tables in same PHP files, So i have used $table_name as the form ID to differentiate the FORMS, and In the del.php ( Where my form get submitted ) I decide which table should I look up to delete the row using the PRIMARY KEY. My Problem is Do I have to create Forms Within each table to do this task? or can I simply put some fields and submit the form using jQuery?
我正在使用 PHP 函数将任何 2D PHP 数组格式化为 HTML 表,在该表中我需要在每一行中添加一个删除按钮,因此当用户单击删除按钮时,jQuery 应采用特定字段(3 个字段)并提交一个 php 文件,它应该在不重新加载页面的情况下给出响应,我在同一个 PHP 文件中有几个动态表,所以我使用 $table_name 作为表单 ID 来区分表单,并在 del.php 中(我的表单在哪里提交)我决定应该查找哪个表以使用 PRIMARY KEY 删除该行。我的问题是我是否必须在每个表中创建表单才能完成此任务?或者我可以简单地放置一些字段并使用 jQuery 提交表单吗?
Any help would be much appreciable .
任何帮助将是非常可观的。
function formatArrayToTable($foo, $deletable = 0, $restaurant_id ='', $table_name = '') {
//open table
echo '<table class="imagetable">';
// our control variable
$first = true;
foreach($foo as $key1 => $val1) {
//if first time through, we need a header row
if($first){
echo '<tr>';
foreach($val1 as $key2 => $value2) {
echo '<th>'.$key2.'</th>';
}
if($deletable) {
echo "<th>'Delete'</th>";
}
echo '</tr>';
//set control to false
$first = false;
}
echo '<tr>';
foreach($val1 as $key2 => $value2) {
echo '<td>'.$value2.'</td>';
}
if($deletable) {
$primary = $val1["id"];
echo "<input type='hidden' name='table_name' value='{$table_name}' />";
echo "<input type='hidden' name='restaurant_id' value='{$restaurant_id}' />";
echo "<td><input class='delete_class' type=\"button\" name=\"delete_id\" value={$primary} onclick='SubmitForm($table_name)'/></td>" ;
}
echo '</tr>';
}
echo '</table>';
}
My Javascript Function
我的 JavaScript 函数
function SubmitForm(formId){
var message = "";
$("#"+formId+" input").each(function() {
message += $(this).attr("name");
});
$.ajax({
type: "POST",
url: "del.php",
data: message,
success:
function() {
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>Entry is Deleted </p>")
.hide()
}
});
}
-Regards
-问候
回答by loushou
Your question seems to ask if you can remove items from a DB using just jQuery. Conventionally, as far as I know, this is not doable, because your DB is server-side and your jQuery is client-side. That being said, I am sure some kook has created a library for it. Despite that, to answer your actual question:
您的问题似乎是在问您是否可以仅使用 jQuery 从数据库中删除项目。通常,据我所知,这是不可行的,因为您的数据库是服务器端而您的 jQuery 是客户端。话虽这么说,我相信有些 kook 已经为它创建了一个库。尽管如此,要回答您的实际问题:
You need to know how you can use jQuery to simulate direct removal of a table row from a DB table. Here is a rough example of your needed jQuery, a sample output of your current php function, and something that should live in del.php to handle the actual delete.
您需要知道如何使用 jQuery 模拟从数据库表中直接删除表行。这是您需要的 jQuery 的粗略示例、当前 php 函数的示例输出,以及应该存在于 del.php 中以处理实际删除的内容。
Example Table
示例表
Quick notes. Add thead and tbody tags to help browsers with the displaying. Remove the onclick=""
bit, you are using jQuery, so just add your callbacks with a JavaScript block. Make sure your code adds the `.submittable' class (or other descriptive name) to your table. You couldwrap the whole table in a form, then use a plugin like jquery formto handle submissions of each form, but that seems like overkill for only handful of fields, so I will explain how to do it with the raw materials.
快速笔记。添加 thead 和 tbody 标签以帮助浏览器进行显示。删除该onclick=""
位,您正在使用 jQuery,因此只需使用 JavaScript 块添加您的回调。确保您的代码将“.submittable”类(或其他描述性名称)添加到您的表中。您可以将整个表格包装在一个表单中,然后使用像jquery 表单这样的插件来处理每个表单的提交,但这对于少数字段来说似乎有点过分,所以我将解释如何使用原材料来完成。
<table class="imagetable submittable">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>file</th>
<th>meta</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type='hidden' name='table_name' value='secret_image_table' />
<input type='hidden' name='restaurant_id' value='123' />
<input class='delete_class' type='button' name='delete_id' value="Delete" />
</td>
<td>Silly Cat Image</td>
<td>yarny-cat.jpg</td>
<td>{"submitter":"De Zéro Toxin"}</td>
</tr>
</tbody>
</table>
jQuery code block
jQuery 代码块
It is a terrible idea to submit your table name from any client-side form, ajax or otherwise. That is super sensitive information, and any programmer/hacker could use that knowledge to their advantage when trying to attack your site. Despite that, I don't know the usage of this, so it may be fine in your setting. Still bad practice though.
从任何客户端表单、ajax 或其他形式提交表名是一个糟糕的主意。这是非常敏感的信息,任何程序员/黑客在尝试攻击您的网站时都可以利用这些知识。尽管如此,我不知道它的用法,因此在您的设置中可能没问题。尽管如此,仍然是不好的做法。
// any time any element with the 'delete_class' on it is clicked, then
$(document).on('click', '.delete_class', function(e) {
var row = $(this).closest('tr');
var data = {
table: $('[name="table_name"]').val(),
id: $('[name="restaurant_id"]').val()
};
$.post('del.php', data, function(r) {
// do some special stuff with your json response 'r' (javascript object)
...
// do what you showed us you are doing, displaying a message
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>Entry is Deleted </p>")
.hide();
// remove the row, since it is gone from the DB
row.remove();
}, 'json');
});
del.php
删除文件
Again, table_name on submission = bad-idea. Horse beaten.
同样,提交时的 table_name = 坏主意。马被打。
// define a delete function that accepts a table name an id
// define some functions to sanitize your $_POST data, to prevent SQL Injection.
// run said functions before you get to this point
// json response function, since you said you want a response from your js
function respond($data) {
echo @json_encode($data);
exit;
}
if (empty($_POST)) respond(array('error' => 'Invalid request'));
$table_name = $_POST['table_name'];
$id = $_POST['id'];
$response = deleteRecord($table_name, $id);
if ($response == $what_you_expect_on_a_successful_delete) {
// create a response message, in associative array form
$message = array('success' => true);
// add some other information to your message as needed
$message['sideNote'] = 'I like waffles.';
// respond with your message
respond($message);
}
// if we got this far your delete failed
respond(array('error' => 'Request Failed'));
Hope this helps.
希望这可以帮助。
回答by Allen King
If you really want to use jQuery to delete a row in a DB directly, you will need to establish a DB connection from jQuery. Not such a bright idea. Instead, you should have a server side function to do the job and call that function using an AJAX call from jQuery.
如果你真的想使用jQuery直接删除数据库中的一行,你需要从jQuery建立一个数据库连接。不是一个好主意。相反,您应该有一个服务器端函数来完成这项工作,并使用来自 jQuery 的 AJAX 调用来调用该函数。