例如,我是一个用户,我想发表评论,并提交后保存到我的数据库。管理的另一个页面更新并自动显示我插入的数据,而不刷新管理的页面。请帮忙. .任何代码都可以提供帮助。谢谢。我使用php作为服务器端语言。任何语言都可以帮助javascript或ajax。
Javascript (jQuery):
$.post('path_to_your_php_script.php', function(data) {
$('the_dom_element_you_want_to_show_the_comment_in').html(data);
});
path_to_your_php_script.php:
// some code to save the data
echo '<div>New comment</div>';
exit;
更多信息,请参考jQuery的post和ajax方法。没有jQuery也可以做到同样的事情,但是不应该重新发明轮子。
yourphpfile.php
是php文件,您需要在其中执行所有数据库操作(在您的情况下是将其插入数据库)。基本上,你想要在不刷新页面的情况下显示最近插入的数据,为此,我们需要Ajax。
因此,在yourphpfile.php
中执行插入操作,如果插入操作成功,则使用echo $output;exit;
返回结果(插入到DB中的数据)其中$output = '最近插入的数据';这就是你在php端需要做的。
你的yourphpfile.php
:
<?php
//your database insert operation
echo $output;// $output should have the inserted data
exit;
?>
现在在ajax函数:
可以使用jquery.ajax
$.ajax({
type: "GET",
url: "yourphpfile.php",
success: function(response){
if(response != '') {
//data that I inserted displays without refreshing the page of the admin
$('yourDivContent').html(response);
} else {
// response error
}
}
});
在响应变量中,您将获得在yourphpfile.php
中响应的内容。这就是$output。然后,您可以使用ajax函数中的响应变量,并使用它来插入到HTML中。
假设您有一个表单,并且可以使用Ajax将数据发送到后端。ajax调用应该是这样的:
var id = $(this).attr('id');
$.ajax({
type:"POST",
url:"ajax.php",
data:{id:id},
success:function(data){
// do something if insertion into database has succeeded
}
});
…PHP中可以这样写:
// Connecting to Database
mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS) or die ('Can not connect to MySQL database');
// Selecting Database
mysql_select_db(DBNAME) or die ('Cant select Database');
$action = mysql_real_escape_string($_POST['action']);
if ($action == "insert")
{
foreach ($recordArray as $key=>$value) {
$query = "INSERT INTO `TABLE`
SET name = `".$_POST['name']."`
SET age = `".$_POST['age']."`
.
.
mysql_query($query) or die('Error, insert query failed');
}