是否可以验证输入是否为空?
我想检查数据是否已从html获取值。如果为true,则应禁用按钮。如果没有,请不要禁用按钮。
这是示例html
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<form method="post">
<label>email
<input type="text" name="email" />
</label>
</form>
</body>
</html>
那是示例html
<script>
$(document).ready(function () {
$("#Submit").click(function(event) {
Execute();
});
function Execute(){
$.ajax({
type: 'POST',
url: 'test.php',
data: { 'email': $("input[name='email']").val() },
success: function(res) {
if (data) {
$("#Submit").attr("disabled", true);
$('#success').text(res.response);
} if (!data) {
$("#Submit").attr("disabled", false);
$('#error').text(res.error_msg);
} else { // do nothing }
},
error: function(resp) {
alert("failed");
}
});
};
});
</script>
答案 0 :(得分:0)
U可以在触发ajax请求之前验证值。因为您可以序列化表单数据,然后验证请求的所需值,如果它们有效,则使用所需数据触发ajax调用
function Execute(){
// Contains all the inputs that are present in your form
var formData = $('form').serializeArray();
// Validate your values
// If values does not matches your requirements, return false with error like
alert('All required values not filled');return false;
// If code reaches here, means you have all your required values.
// So, making ajax request makes more sense now as it can be executed successfully as values are first validated then ajax is triggered
$.ajax({
// Your code for ajax request
})
}
答案 1 :(得分:0)
尝试这个。我刚刚修改了您的代码。希望它可以帮助您。基本上,只有在您验证值之后才调用ajax调用,一旦您验证了值,就可以继续使用ajax并使用ajax生命周期函数处理按钮状态(我不知道这些的确切用语(beforeSend,complete,success等) ):)
答案 2 :(得分:0)
大声笑像这样更容易
我固定了D :)
仅在发送之前是解决方法
<script>
$(document).ready(function () {
$("#Submit").click(function(event) {
Execute();
});
function Execute(){
$.ajax({
type: 'POST',
url: 'test.php',
data: { 'email': $("input[name='email']").val() },
beforeSend: function(){
if ($("form input[name='email']").val() == "") {
alert("Text-field is empty.");
return false;
}
},
success: function(response) {
$("#Submit").attr("disabled", true);
$('#resp').text(response.feedback);
},
error: function() {
alert("failed");
}
});
};
});
</script>