想象一下提交评论表单后页面总是刷新。这很烦人,因为评论不在页面顶部,您总是必须滚动到底部才能看到您的评论和其他评论。
我觉得使用ajax提交表单会好很多。
HTML
<form id="com-form" method="post">
<textarea type="text" name="text" required=""></textarea>
<input type="submit" value="Post"/>
</form>
<div id="com-refresh"></div>
jQuery
$("#com-form").on('submit', function(e) {
e.preventDefault();
var form = $(this),
form_data = form.serialize();
$.post('/php/comments/add.php', form_data, function(data) {
$("#com-refresh").append(data);
});
});
PHP
<?php
session_start();
require_once 'comment.class.php'; //require a class with methods
$text = $_POST['text'];
if($_SESSION['status'] == 'loggedin') {
if(isset($text)) {
$comment = new Comment(); //initialize the Comment object
echo $comment->add_comment($text); //safe the comment in the database and output it
} else echo "Your comment is empty.";
} else echo "Please log in to post comments.";
我希望代码是可以理解的。
您认为使用 ajax 在提交表单后不刷新页面是聪明还是坏做法?
应该怎么做呢?您有更好的想法、更干净的解决方案吗?
最佳答案
你可以简单地这样做:
$(document).ajaxSuccess(function(e, xhr, settings) {
$(".mydiv").html(xhr.responseText);
});
让你的 php 文件打印你想要替换的 html。
进一步阅读:ajaxSuccess
您的解决方案的示例
表单文件:
<form method="post">
<textarea type="text" name="comment" id="com-area"></textarea>
<input type="submit" id="com-submit"/>
</form>
<div id="com-refresh">
<?php require_once "comments/build.php"; ?>
</div>
$(function() {
$(".cmtx_form").submit(function(e) {
e.preventDefault();
var form = $(this);
var text = $(".cmtx_textarea_field").val();
$.ajax({
type: 'POST',
url: 'comments/add.php?ajaxCall=true',
cache: false,
data: { comment: text }
});
});
});
$(document).ajaxSuccess(function(e, xhr, settings) {
$("#com-refresh").html(xhr.responseText);
});
你的 add.php 文件应该看起来像这样:
// ... code code code...
if (isset($_GET['ajaxCall']) && $_GET['ajaxCall']) {
include_once('/path/to/build.php');
}
关于javascript - 我应该将 PHP 与 ajax 结合起来将数据发送到服务器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23385804/