我有一个HTML表单,其中包含用户名文本框和提交按钮。
当用户在用户名文本框中输入名称时,我想获取该值并将其发送到服务器,以便我可以检查该用户名是否已被其他用户使用。
以下是我创建表单的代码:
<!DOCTYPE html>
<html>
<head>
<script src="JquerySock.js"></script>
<meta charset="utf-8" name="viewport" content="width=device-width, initial- scale=1">
<script>
function Usernameerrorfunc(field, errordiv, Notallowcharserror_SPN){
}
</script>
</head>
<body>
<div id="Registeration_Div" class="Registeration_Div">
<form class="Registration_Form" id="Registration_Form" action="../postr" method="POST">
<div id="Registeration_Username_DIV" class="Registeration_Username_DIV">
<input type="text" id="Registeration_Username_box" class="Registeration_Username_box"
placeholder="" name="UserName" maxlength="30" onblur="Usernameerrorfunc(this, 'Usernameerror_spn', 'Usernamenowallow_spn');" onclick="textboxfocus(this)"/>
</div>
<div class="Registration_Submit_Div">
<input type="submit" value="Submit" id="SumbitForm_btn" class="SumbitForm_btn" name="Submit_btn"/>
</div>
</form>
</div>
</body>
</html>
答案 0 :(得分:2)
您可以在jQuery中使用$.ajax
方法:
function postUsernameToServer() {
var username = $("#Registeration_Username_box").val();
$.ajax({
url: "http://YourServerUrl",
type: "POST",
data: { username: username },
success: function() {
alert('Successfully connected to the server');
},
error: function() {
alert('Something went wrong');
}
});
}
要使用按钮单击(从我的评论中)调用此项,您可以执行以下操作:
<button id="checkUsername">Check username</button>
$("#checkUsername").on("click", function() {
postUsernameToServer();
});
确保已导入jQuery库以使用该功能。 如果您不想使用jQuery而非本机JavaScript,则可以使用XMLHttpRequest。
答案 1 :(得分:0)
试试这个会起作用:
代码:
function submitFormData() {
var name = document.getElementById("Registeration_Username_box").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username=' + name;
if (username == '') {
alert("Please Enter the Username");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "checkUsername.php",
data: dataString,
cache: false,
success: function(data) {
alert(data);
},
error: function(err) {
alert(err);
}
});
}
return false;
}
我在php
中提供示例来检查用户名。您可以相应地使用任何语言。
checkUsername.php:
<?php
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("dbname", $connection); // Selecting Database
//Fetching Values from URL
$username=$_POST['username'];
//Select query
$query = 'select * from user_table WHERE name = "'.$username.'";
$query_result = mysql_query($query);
$res = mysql_fetch_assoc($query_result);
do
{
echo json_encode($res);
}while($res = mysql_fetch_assoc($query_result));
}
mysql_close($connection); // Connection Closed
?>