指出:
我有两张桌子彼此相邻。 其中一个是数据填充(在这种情况下,一个表格中填充了团队中所有人的名字)。 另一个是空的。现在,我想拖放另一个表中的名称(行)和上的,它会触发插入 - 查询到数据库。
此外,第一个表中填充数据的名称始终保持不变(名称列表永远不会更改)。
所以,一个小方案:
表填充了来自数据库的数据(拖动)
空表(丢弃)
正在将名称从第一个表拖到第二个表,并且在删除时,会向数据库发出插入查询。在刷新页面时,仍会在第二个表中看到删除的名称。
哦,还有一个可选项应该实现的功能:如果我将第二个表中的名称拖回第一个名称,名称应该会消失(因此会从数据库中的表中删除记录)。拖放应该可以在两个方向上使用。
我已经拥有的代码,但不知何故不起作用:
$(document).ready(function() {
var $tabs = $('#EmptyTable')
$("tbody.t_sortable").sortable({
connectWith: ".t_sortable",
items: "> tr:not(:first)",
appendTo: $tabs,
helper:"clone",
zIndex: 999990
}).disableSelection();
var $tab_items = $(".nav-tabs > li", $tabs).droppable({
accept: ".t_sortable tr",
hoverClass: "ui-state-hover",
drop: function( event, ui ) {
<?
mysql_query("INSERT INTO emptyTable_team (name) values (<datafromfirsttable>)");
?>
return false;
}
});
});
答案 0 :(得分:2)
您无法将PHP函数插入Javascript。
PHP是一种脚本语言,它告诉您的Web服务器如何处理请求,例如更新数据库或呈现HTML。但是一旦处理了请求,PHP脚本就会停止,所有变量都会被卸载等等。
您在PHP中编写的脚本告诉Apache在页面加载时运行该查询一次。
您要做的是在drop函数中调用$.ajax。 jQuery的ajax函数可以将数据POST到url,此时你可以通过将数据插入数据库来处理请求。
<强>使用Javascript:强>
$(document).ready(function() {
var $tabs = $('#EmptyTable');
$("tbody.t_sortable").sortable({
connectWith: ".t_sortable",
items: "> tr:not(:first)",
appendTo: $tabs,
helper:"clone",
zIndex: 999990
}).disableSelection();
var $tab_items = $(".nav-tabs > li", $tabs).droppable({
accept: ".t_sortable tr",
hoverClass: "ui-state-hover",
drop: function( event, ui ) {
var rowData;
// looping through the cell of each row
for (var i = 0; i < $("td",this).length; i++) {
// Get the name of the column
// I don't know your HTML so I can't make a selector for this
var colName = $("selector-for-header-column").text();
// Using square brackets to access an object property by string variable,
// and selecting the text in this cell for the dropped row.
rowData[colName] = $("td",this).eq(i).text();
}
// Now we have an object whose property names are the table headers,
// and the data in each property is the text in each cell of the dropped row.
$.ajax({
type: "POST",
url: "/insertTeamMember.php",
data: rowData,
success: function (data) {
// Log the return from the ajax endpoint, this will help you debug!
console.log(data);
}
});
}
});
});
<强> insertTeamMember.php:强>
<?PHP
$dbcO = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$q = "INSERT INTO emptyTable_team (name) values ( ? )";
$stmt = $dbcO->stmt_init();
$stmt->prepare($q);
$stmt->bind_param('s', $_POST['name']);
$stmt->execute();
$stmt->close();
?>
我使用了prepared statement作为防止mysql注入的简单方法。强烈建议永远不要将用户输入直接插入查询字符串。用户输入是来自客户端的所有数据。