简单的Javascript评论表格

时间:2014-10-24 03:10:04

标签: javascript webforms textarea commenting

我有一个textarea和一个提交按钮。

单击该按钮时,我希望将textarea的值放在容器中(在段落标记中)。我希望这个值存储在我的网络服务器上。

我该怎么写?

由于

1 个答案:

答案 0 :(得分:0)

这只是你的起点。以下工作100%,但你也需要做一些工作

html -

<div id="MyComments"></div>
<input type="text" id="name"/>
<textarea id="comment"></textarea>
<input type="submit" id="" value="Go!" onclick="comment();"/>

使用Javascript -

function comment(){
//Store elements in a variable.
var name= document.getElementById("name");
var comment= document.getElementById("comment");
//I would recommend checking/validating the users input.
var hr = new XMLHttpRequest();
//Sending the comment to AddComment.php
var url = "AddComment.php";
var vars = "name="+name.value+"&comment="+comment.value;
    hr.open("POST", url, true);
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
    var return_data = hr.responseText;
/*Comment post successfully sent.
return_data = your php reply, you can append a new element to your webpage to 
display the php result/comment.
Remove loading icon if you have added.*/
var target = document.getElementById('MyComments');
var ElementType = document.createElement('p');
//Set attributes to your element /onclick/ID/Class/style(in-line style)
ElementType.setAttribute('align', 'center');
target.appendChild(ElementType);
//Insert the php result into the new P element.
ElementType.innerHTML=return_data;
}}
//Send the comment to the php
hr.send(vars);
//Here you can display a loading icon.
}

PHP -

<?php
if(isset($_POST['name'])&&($_POST['comment'])){
die('<b>'.$_POST['name'].':</b> <i>'.$_POST['comment'].'</i>');
}
?>

从这里你需要做的就是验证javascript中的用户输入,在保存之前在php中验证服务器端(更好的是安全而不是抱歉)。您将不得不考虑自己保存评论的方法,但我个人会使用MYSQL。 希望这是一个很好的起点! 如果这回答了您的问题,请标记此帖。