確定現在下面是我的代碼,當一些機構提出的用戶名和密碼,然後單擊提交按鈕,然後在JavaScript和Ajax被觸發AJAX加載不正常
<html>
<head>
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function() {
$('form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'redirect.php',
data: $('form').serialize(),
success: function() {
alert('form was submitted');
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form>
<div class="add_list">
<p><span>Select User Name : </span>
<input type="text" name="username" size="20" />
</p>
<p><span>Select Your Password : </span>
<input type="password" name="password" size="20" />
</p>
</div>
<div class="add_user">
<input type="submit" value="add user" />
</div>
</form>
</body>
</html>
其被觸發後,加載這個頁面是redirect.php頁
<?php
include 'includes\config.php';
//connects to the database
if (!empty($_POST['username']) && !empty($_POST['password'])) {
// Now checking user name and password is entered or not.
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$check = "SELECT * from user where username= '" . $username . "'";
$qry = mysql_query($check);
$num_rows = mysql_num_rows($qry);
if ($num_rows > 0) {
// Here we are checking if username is already exist or not.
echo "The username you have entered already exist. Please try again with another username.";
echo ('<script type="text/javascript"> alert ("The username you have entered already exist. Please try again with another username.");</script>');
exit;
}
// Now inserting record in database.
$query = "INSERT INTO user VALUES ('','" . $username . "','" . $password . "')";
//id,username and password
mysql_query($query);
echo "User Added Successfully";
echo ('<script type="text/javascript"> alert ("The username is added successfully.");</script>');
exit;
}
?>
現在的問題是,當我提交表單它提醒該表單提交,但實際的JavaScript這是redirect.php沒有加載未報警,也儘管它正在變得越來越多,但php的回聲也不起作用在數據庫中提交,另一個問題是,如果該用戶名已經存在,當一個人輸入表單提交時是警報,然後什麼也沒有,當我檢查它沒有得到提交作爲用戶名已存在,但沒有回聲或警報的JavaScript工作。
當你通過ajax提交時,瀏覽器不會重定向,這幾乎是整個點 – Steve
你意識到你使用的是ajax,並且表單實際上不會被提交,也不會加載頁面,也沒有什麼會發生,除非你讓它發生? – adeneo
請看這裏 - http://stackoverflow.com/questions/75943/how-do-you-execute-a-dynamically-loaded-javascript-block –