gpt4 book ai didi

javascript - 清除表单并显示新评论 jquery php

转载 作者:行者123 更新时间:2023-11-30 00:03:32 24 4
gpt4 key购买 nike

我正在尝试制作一个评论表单,将评论放入我的 mysql 数据库中,并在提交后立即将新评论放入我的页面上(并清除表单)。但不知何故,您必须始终刷新才能看到新评论,如果您多次单击“提交”,刷新后会显示重复的评论。我该如何解决这个问题?我有点菜鸟,所以我的代码大部分来 self 还没有完全理解的教程......

我的 php 页面:

<?php

// Error reporting:
error_reporting(E_ALL^E_NOTICE);

include "connect.php";
include "comment.class.php";

$comments = array();
$result = mysql_query("SELECT * FROM comments ORDER BY id ASC");

while($row = mysql_fetch_assoc($result))
{
$comments[] = new Comment($row);
}

?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Bausatz</title>
<meta name="" content="">

<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/modernizr-2.7.1.min.js"></script>
<style type="text/css"></style>


<link href='http://fonts.googleapis.com/css?family=Montserrat:400' rel='stylesheet'
type='text/css'>
</head>


<body>

<header>
<div class="logo">
<span class="col">ON THE </span>W<span class="col">OODWAY</span>
</div>

<nav>
<a href="travels.html">TRAVELS</a>
<a href="blog.html">BLOG</a>
<a href="me.html">ME</a>
</nav>
</header>

<div class="main">


<div class="contentwrapper">

<div class="entry">
</div>


<div class="comment">

<div id="each">
<?php
foreach($comments as $c){
echo $c->markup();
}
?>
</div>


<div id="addCommentContainer">
<p>Add a Comment</p>
<form id="addCommentForm" method="post" action="">
<div>
<label for="name">Your Name</label>
<input type="text" name="name" id="name" />

<label for="email">Your Email</label>
<input type="text" name="email" id="email" />

<label for="body">Comment Body</label>
<textarea name="body" id="body" cols="20" rows="5"></textarea>

<input type="submit" id="submit" value="Submit" >
</div>
</form>

</div>

</div>




</div>
</div>






<div class="unten">
<nav>
<a href="#">contact</a>
<a href="#">copyright</a>
</nav>
</div>






<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-1.9.1.min.js">
<\/script>')</script>
<script type="text/javascript" src="js/comment.js"></script>
</body>
</html>

jQuery:

$(document).ready(function(){

var working = false;

$('#addCommentForm').submit(function(e){

e.preventDefault();
if(working) return false;

working = true;
$('#submit').val('Working..');
$('span.error').remove();

/* Sending the form fileds to submit.php: */
$.post('submit.php',$(this).serialize(),function(msg){

working = false;
$('#submit').val('Submit');


if(msg.status){

$(msg.html).hide().insertBefore('#addCommentContainer').slideDown();
$('#body').val('');
}
else {

$.each(msg.errors,function(k,v){
$('label[for='+k+']').append('<span class="error">'+v+'</span>');
});
}
},'json');

});

});

comment.class.php

<?php

class Comment
{
private $data = array();

public function __construct($row)
{
/*
/ The constructor
*/

$this->data = $row;
}

public function markup()
{
/*
/ This method outputs the XHTML markup of the comment
*/

// Setting up an alias, so we don't have to write $this->data every time:
$d = &$this->data;

$link_open = '';
$link_close = '';



// Converting the time to a UNIX timestamp:
$d['dt'] = strtotime($d['dt']);

return '

<div class="comment">

<div class="name">'.$link_open.$d['name'].$link_close.'</div>
<div class="date" title="Added at '.date('H:i \o\n d M
Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
<p>'.$d['body'].'</p>
</div>
';


}

public static function validate(&$arr)
{
/*
/ This method is used to validate the data sent via AJAX.
/
/ It return true/false depending on whether the data is valid, and populates
/ the $arr array passed as a paremter (notice the ampersand above) with
/ either the valid input data, or the error messages.
*/

$errors = array();
$data = array();

// Using the filter_input function introduced in PHP 5.2.0

if(!($data['email'] = filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)))
{
$email = '';
}



// Using the filter with a custom callback function:

if(!($data['body'] =
filter_input(INPUT_POST,'body',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))) )
{
$errors['body'] = 'Please enter a comment body.';
}

if(!($data['name'] = filter_input(INPUT_POST,'name',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
{
$errors['name'] = 'Please enter a name.';
}

if(!empty($errors)){

// If there are errors, copy the $errors array to $arr:

$arr = $errors;
return false;
}


foreach($data as $k=>$v){
$arr[$k] = mysql_real_escape_string($v);

}


$arr['email'] = strtolower(trim($arr['email']));

return true;

}

private static function validate_text($str)
{

if(mb_strlen($str,'utf8')<1)
return false;

$str = nl2br(htmlspecialchars($str));

$str = str_replace(array(chr(10),chr(13)),'',$str);

return $str;
}

}

?>

提交.php

<?php

error_reporting(E_ALL^E_NOTICE);

include "connect.php";
include "comment.class.php";



$arr = array();
$validates = Comment::validate($arr);

if($validates)
{

mysql_query(" INSERT INTO comments(name,url,email,body)
VALUES (
'".$arr['name']."',
'".$arr['url']."',
'".$arr['email']."',
'".$arr['body']."'
)");

$arr['dt'] = date('r',time());
$arr['id'] = mysql_insert_id();


$arr = array_map('stripslashes',$arr);

$insertedComment = new Comment($arr);



echo json_encode(array('status'=>1,'html'=>$insertedComment->markup()));


}
else
{
echo '{"status":0,"errors":'.json_encode($arr).'}';
}

?>

连接.php

<?php

$db_host = '*****';
$db_user = '*****';
$db_pass = '*****';
$db_database = '*****';



$link = @mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');

mysql_query("SET NAMES 'utf8'");
mysql_select_db($db_database,$link);

?>

最佳答案

为什么不尝试将其附加到其余评论中呢?

更改此:

$(msg.html).hide().insertBefore('#addCommentContainer').slideDown();

对此:

$(msg.html).hide().appendTo('#each').slideDown();

关于javascript - 清除表单并显示新评论 jquery php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24802099/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com