基本上我有一个带有用户名文本框和提交按钮的表单。现在我想要的是,当用户在文本框中输入文本时,它应该获取文本框值并将用户名发送到服务器,以便服务器可以检查该用户名是否被任何其他用户占用。我可以将文本值发送到服务器,但我不知道如何接收回一些数据并将文本框边框变成红色,并在用户名被占用时弹出错误。
这是我获取文本值并将其发送到服务器的代码:
<!DOCTYPE html>
<html>
<head>
<script src="../JquerySock.js"></script>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1">
<script>
$(document).ready(function() {
$('#Registeration_Username_box').on('input', function() {
console.log('excuted input');
postUsernameToServer();
});
});
function postUsernameToServer() {
var formData = {
'username': $('input[name=UserName]').val(),
};
// process the form
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: '../postr', // the url where we want to POST
data: formData, // our data object
dataType: 'json', // what type of data do we expect back from the server
encode: true
})
}
</script>
</head>
<body>
<div id="Registeration_Div" class="Registeration_Div">
<div class="createnewaccount" id="createnewaccount">Create new account</div>
<form class="Registration_Form" id="Registration_Form" action="../postr" method="POST">
<span class="Usernameerror_spn" id="Usernameerror_spn">Username has been taken</span>
<div id="Registeration_Username_DIV" class="Registeration_Username_DIV">
<input type="text" id="Registeration_Username_box" class="Registeration_Username_box"
placeholder="Username" name="UserName" maxlength="30" />
</div>
</form>
</div>
</body>
</html>
正如您所看到的,我的用户名文本框之前有一个范围框,默认情况下是隐藏的,但我希望如果用户已被占用,则显示它。
嗯,首先:
您要求数据类型是JSON
。这意味着在服务器端(是 PHP 吗?),您必须首先将其转换为 JSON 对象。在 PHP 中这将是
$data = array("username" => "bla", "taken" => "taken");
echo json_encode($data);
对于 Java EE,你可以使用这个:(source https://stackoverflow.com/questions/6185337/how-do-i-pretty-print-existing-json-data-with-java)
int spacesToIndentEachLevel = 2;
new JSONObject(jsonString).toString(spacesToIndentEachLevel);
Using org.json.JSONObject
(内置于 JavaEE 和 Android)
现在,您必须确保它仅返回所需的内容JSON
没有别的,否则你会得到错误。
然后,要在 ajax 调用中获取反馈:
function postUsernameToServer() {
var formData = {'username': $('input[name=UserName]').val()};
// process the form
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: '../postr', // the url where we want to POST
data: formData, // our data object
dataType: 'json', // what type of data do we expect back from the server
encode: true
}).done(function(data){ //any name you put in as an argument here will be the json response string.
var username = data.username;
var taken = data.taken;
//check if username is taken
if(taken == "taken"){
//make input border red
$('.yourInput').css({"border-color": "red"});
}
else{
//make input border green
$('.yourInput').css({"border-color": "green"});
}
}).error(function(errorData){
//Something went wrong with the ajax call. It'll be dealt with here
});;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)