如何在PHP中使用单击的元素的内部HTML,如下所述?
$(function () {
$(".topic-list-items").click(function () {
// document.getElementById("content-of-the-topic").innerHTML= $(this).context.innerHTML;
<?php
$dbhost = '127.0.0.1';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die('Could not connect: '.mysql_error());
}
// here I want to table name dynamically, that is, "SELECT id FROM table". $variable
$sql = "SELECT id FROM ";
//$ variable is the clicked element's innerHTML
mysql_select_db('entries_database');
$retval = mysql_query($sql, $conn);
if (!$retval) {
die('Could not get data: '.mysql_error());
}
?>
});
});
您需要对PHP脚本进行AJAX调用,并将元素的内容作为数据参数。
data: {my_data: $(".topic-list-items").html()}
或者,如果你有更多的内容,你可以使用$(this)
:从点击功能中获取内容
$(".topic-list-items").click(function () {
data: {my_data: $(this).html()}
...
})
然后,您可以使用$_POST['my_data']
之类的东西从PHP访问它。
这里有一个例子:
$.ajax({
type: "POST",
url: "my_php_script.php",
data: {my_data: $(".topic-list-items").html()}
}).done(function( msg ) {
alert( "PHP says: " + msg ); // you can do whatever you want here
});
编辑
请停止使用mysql_*函数,因为它们已被弃用。请参见此处:http://www.php.net/manual/en/function.mysql-query.php
此外,请注意通过过滤任何输入来进行SQL注入(尽管输入来自DOM元素,但它很容易转换为数据库攻击)。
php运行在服务器端,javascript运行在客户端。如果您想将这些值提供给php,则需要将它们提交回服务器。
看看ajax。
您不能只将服务器端的php代码放入客户端的JScript代码中并期望它被执行。它是可以做到的,尽管通常不是这样实现的。
如果您已经在使用JQuery,请从使用JQuery.get()等AJAX函数开始。从JQuery.load()等简写函数开始可能会更容易,以便对这些函数的工作原理有第一印象。手册中也有一些很好的例子。
您可以使用jquery ajax函数
//the get method
$.get('file.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
http://api.jquery.com/jQuery.get/
//the load function
$('#result').load('file.php');
http://api.jquery.com/load/
在HTML中添加一个带有#hiddenElementId的隐藏表单元素,然后将值分配给任何你喜欢的值,并提交表单。这将把参数发布到你的php目标。
var myInnerHTML;
$(".topic-list-items").click(function() {
myInnerHTML= $(this).context.innerHTML;
$("#hiddenElementId").val(myInnerHTML);
$("#formId").submit();
}