我有一个包含PHP代码的div(它从数据库打印数据)。我创建了一个AJAX函数来将数据发送到服务器而不刷新页面,这里是代码:
var url = "loadsave.php";
$('.create_save').submit(function(event) {
if ($('.gss_new_save').val()==""){
event.preventDefault();
} else {
$.ajax({
type: "POST",
url: url,
data: $('form').serialize(),
success: function()
{
}
});
event.preventDefault();
}
});
这是打印代码的另一部分。问题是它只是在刷新页面时打印代码:
<?php
$connect = new PDO('mysql:host=localhost;dbname=game','root','');
$cmd = $connect->query('SELECT * FROM saves');
$result = $cmd -> fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $res) {
?>
<div class="gss_save cls">
<span class="gss_save_text cls"><?php echo $res['name'];?></span>
<span class="gss_level">lvl: <?php echo $res['level'];?></span>
</div>
<?php
}
?>
编辑:我补充说:表格:
<form method="post" action="loadsave.php" class="create_save">
<input type="text" class="gss_new_save" name="name">
<input type="submit" style="display:none">
</form>
和loadsave.php的内容:
<?php
if (isset($_POST['name'])) {
$nombre = $_POST['name'];
}
$connect = new PDO('mysql:host=localhost;dbname=game','root','');
$stm = $connect->query("SELECT * FROM saves WHERE `name` ='$nombre'");
$result = $stm->fetchAll(PDO::FETCH_ASSOC);
if(count($result)==0){
$cmd = $connect->prepare('INSERT INTO saves (name, level) VALUES (:nombre,"1")');
$cmd -> bindParam(":nombre",$nombre);
$cmd -> execute();
}
?>
它就像一个魅力,但我想刷新div来打印我刚发送的内容,我怎样才能实现这个目标?
答案 0 :(得分:2)
假设脚本回显了新内容:
success:function(response) {
$("#divID").html(response);
}
loadsave.php
应该是:
<?php
if (isset($_POST['name'])) {
$nombre = $_POST['name'];
}
$connect = new PDO('mysql:host=localhost;dbname=game','root','');
$stm = $connect->query("SELECT * FROM saves WHERE `name` ='$nombre'");
$result = $stm->fetchAll(PDO::FETCH_ASSOC);
if(count($result)==0){
$cmd = $connect->prepare('INSERT INTO saves (name, level) VALUES (:nombre,"1")');
$cmd -> bindParam(":nombre",$nombre);
$cmd -> execute();
}
$cmd = $connect->query('SELECT * FROM saves');
$result = $cmd -> fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $res) {
?>
<div class="gss_save cls">
<span class="gss_save_text cls"><?php echo $res['name'];?></span>
<span class="gss_level">lvl: <?php echo $res['level'];?></span>
</div>
<?php
}
?>