我有一个单页网站,插入工作正常,但提交后似乎无法更新#results div。这些值被插入到数据库中就好了,如果我硬刷新它们就会出现。但不是用 jQuery AJAX 刷新。我是 Ajax 新手,因此非常感谢任何帮助,以及对代码结构或不良习惯的任何评论,请在我尝试学习正确的编程方法时发表评论。
这是我的代码:
$(document).ready(function(){
$("form#addTodo").submit(function(){
alert('hello world'); // ensure function is running
var post_title = $('input#post_title').val(); // take values from inputs
var post_content = $('input#post_content').val();
$.ajax({
type: "POST",
url: "add.php",
data: "post_title=" + post_title + "&post_content=" + post_content,
success: function() {
// alert('success'); // ensure success
$('#results').fadeOut('slow').load('include/results.php').fadeIn('slow');
}
});
$('input#post_title').val(''); // clear form fields
$('input#post_content').val('');
return false;
});
});
这是 results.php 文件:
<?php
$sql = $db->query('SELECT id, post_title, post_content FROM posts ORDER BY post_title ASC');
$results = $sql->fetchALL(PDO::FETCH_OBJ);
$count_posts = count($results);
?>
<?php if ( have_posts() == true) : ?>
<div class="accordion" id="accordion_main">
<?php foreach($results as $entry): ?>
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion_main" href="#collapse-<?php echo $entry->id; ?>">
<?php echo $entry->post_title; ?>
</a>
</div>
<div id="collapse-<?php echo $entry->id; ?>" class="accordion-body collapse">
<div class="accordion-inner">
<p class="target"><?php echo $entry->post_content; ?></p>
<p><a href="edit.php?id=<?php echo $entry->id; ?>">Edit</a> <a href="delete.php?id=<?php echo $entry->id; ?>" onclick="return confirm('Are you sure you wish to delete this post?');">Delete</a></p>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<?php else: ?>
<h3>There are no posts to display at this time.</h3>
<?php endif; ?>
当它包含在 index.php 中时,它工作正常,我只是无法在将数据发布到数据库后刷新它。
<?php
require_once 'includes/db.php';
require_once 'includes/functions.php';
?>
<?php get_header(); ?>
<div id="results">
<?php include_once 'includes/results.php'; ?>
</div>
<hr />
<p>Add New Post</p>
<form id="addTodo" action="">
<div>
<label for="post_title">Post Title</label>
<input id="post_title" name="post_title">
</div>
<div>
<label for="post_content">Post Content</label>
<input id="post_content" name="post_content">
</div>
<div>
<button id="submit" type="submit">
Save
</button>
</div>
</form>
<?php get_footer(); ?>
我应该提到我还没有进行表单验证。非常感谢任何帮助,谢谢。