是否可以使用javascript来获取用户的文本并将其插入到mysql数据库中?

我有一个带有提交按钮的简单表单(如下)。我想让用户在文本框中键入内容,然后当他/她单击提交时,页面就会刷新并回显他们在div中键入的内容。 用户输入的数据在回显之前已存储在数据库中,问题是,当我单击提交时,输入不会立即显示,我必须单击刷新才能显示它,并且当我这样做时,浏览器会弹出一个窗口(Safari),要求重新发送数据——这就会导致在数据库中插入重复的数据。 我大概知道需要使用javascript,还可以使用fadeIn使它更加优雅,但我不知道该怎么做。所以我想问问是否有一种方法可以使用javascript来获取用户的文本并将其插入到mysql数据库中?并在1或0(最好是刷新)全部单击提交后显示它?谢谢!

这是我的代码:
<form method='POST'  action='index.php'>
<input type='text' name='text' id='text'>
<input type ='submit' value='submit' name='submit'>
</form>

<?php
$input=$_POST['text'];
$put=mysql_query("INSERT INTO table VALUES ('$input')");

echo "<div id='area'>";
//i connect to the DB and echo out the data here

echo "</div>";

?>

Setting aside SQL injection attacks your code is vulnerable with, the standard practice is to respond to the POST with a redirect back to where the form was. In your case, it will be the page which runs SELECT from table.

No need to use AJAX here. Just make sure that you do one of the following:

  1. Make sure you SELECT from the DB after you have INSERTed the data.
  2. Better, is that if ($_SERVER['REQUEST_METHOD'] == 'POST'), then rather than performing an extra SQL query, just display the POSTed value since you already know it.

A side note on your code sample. If you don't have magic_quotes enabled, it's susceptible to SQL injection, so make sure you properly escape user input before using it in queries.

I would put the php statements before you're actual html code and would modify you're code like this

<?php
if (isset($_POST['text']))
{
  $input = mysql_real_escape_string($_POST['text']);

  $put=mysql_query("INSERT INTO table VALUES ('$input')"); //At this point the info has been put inside the DB

  echo "<div id='area'>";
  //i connect to the DB and echo out the data here
  echo mysql_query("SELECT * FROM table");
  echo "</div>";
}
?>

<form method='POST'  action='index.php'>
<input type='text' name='text' id='text'>
<input type ='submit' value='submit' name='submit'>
</form>

The reason why you don't see it is that the HTML is loaded before you php I think. So I would do a php page where all the sql treatement would be done and once that is done recal you index.php and in there query you're information from the database.