我打算在表行上运行查询 onclick 事件。
我在 JavaScript 中创建了一个函数,我可以读取每一行的 id。
现在我希望能够以此 id 作为条件来运行查询。
他们能帮我吗?
明白我的问题吗?
下面我展示了我的代码。
-------------Javascript函数-----------------!
<script>
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("td");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[1];
var id = cell.innerHTML;
alert("id:" + id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
window.onload = addRowHandlers();
</script>
-----我打算运行的查询------------
$result= mysql_query("select * from tasks where idTask = id");
while($row = mysql_fetch_array($result))
{
$image = $row['image'];
header("Content-type:image/jpeg");
echo $image;
}
最佳答案
您需要使用 Ajax 将您的 id
发送到单独的 php 文件,然后返回数据。我使用 jQuery 库,因此本示例使用 $.post()
- ( http://api.jquery.com/jquery.post/ ) 和 jQuery UI .dialog()
- ( http://jqueryui.com/dialog/ ) 弹出类似于 alert()
的结果
JavaScript代码
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("td");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[1];
var id = cell.innerHTML;
//use ajax to post id to ajax.php file
$.post( "ajax.php", { id:id }, function( data ) {
//add result to a div and create a modal/dialog popup similar to alert()
$('<div />').html('data').dialog();
});
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
window.onload = addRowHandlers();
</script>
ajax.php
(单独文件,随机命名为ajax.php
)
$id = mysql_real_escape_string($_POST['id');
$result= mysql_query("select * from tasks where idTask = $id");
while($row = mysql_fetch_array($result))
{
$image = $row['image'];
header("Content-type:image/jpeg");
echo $image;
}
关于javascript - MySQL查询表行上的onclick事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26102461/