我想要一个表单,它可以让我在不刷新表单的情况下将名称添加到我的数据库中。我一直在努力,但它似乎不起作用。我对此很陌生,因此不胜感激。
对于我的 index.html,我有:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var name = $("#firstname").val();
var username = $("#lastname").val();
var dataString = 'firstname='+ firstname + 'lastname=' + lastname
if(firstname=='' || lastname=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
<body>
<form method="post" name="form">
<ul><li>
<input id="firstname" name="firstname" type="text" />
</li><li>
<input id="lastname" name="lastname" type="text" />
</li></ul>
<div >
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div></form>
对于 join.php:
<?php
include("db.php");
if($_POST)
{
$firstname=$_POST['firstname'];
$lastname=$_POST['username'];
mysql_query("INSERT INTO persons (firstname,lastname) VALUES('$firstname','$lastname')");
}
?>
和db.php:
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "test";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>