如果数据为空,我希望返回true;如果数据不为空,则返回false。如果数据为空,则继续使用表单操作,否则保留在当前页面中。
代码是:
<script type="text/javascript">
function error()
{
var response = false;
$.ajax({
url: BASE_URL + 'auth/validateForm',
type: 'POST',
data: {
surname: $("#r-surname").val()
},
dataType: "json",
success: function(data) {
if(data.surname)
{
$('#error_surname').html(data.surname);
response = false;
}else{
$('#error_surname').html('');
response = true;
}
},
error: function(data) {
return false;
}
});
alert(response);
return response;
}
</script>
<form action="{$BASE_URL}contul-meu" method="post" name="registration" onsubmit="return error()">
<table>
<tr>
<td>
<label for="r-surname">Prenume*</label>
</td>
<td>
<input type="text" class="text" id="r-surname" name="surname" value="{$user['surname']}"/>
</td>
<td><small id="error_surname" class="err"></small></td>
</tr>
</table>
</form>
PHP:
public function validateForm()
{
$surname = $this->input->post('surname');
$data = array();
if(strip_tags($surname) == '')
{
$data['surname'] = 'Prenumele este invalid!';
}
echo json_encode($data);
}
var response仅为false。如果没有错误,如果生成响应是真的吗?
答案 0 :(得分:2)
您无法返回嵌套ajax函数的结果。 javascript将执行并继续 - 但是在函数返回后发生请求的延迟。
最好的事情是连结你的活动。只需创建另一个接受true或false值的函数,并将逻辑包装在那里。
<script type="text/javascript">
function error()
{
var response = false;
$.ajax({
url: BASE_URL + 'auth/validateForm',
type: 'POST',
data: {
surname: $("#r-surname").val()
},
dataType: "json",
success: function(data) {
if(data.surname)
{
$('#error_surname').html(data.surname);
response = false;
doSomethingBasedOnResponse(false);
}else{
$('#error_surname').html('');
response = true;
doSomethingBasedOnResponse(true);
}
},
error: function(data) {
return false;
doSomethingBasedOnResponse(false);
}
});
}
function doSomethingBasedOnResponse(value){
if(value){
alert('yes');
}else{
alert('no');
}
}
</script>
答案 1 :(得分:0)
在表单中添加ID
<form id="registration"..
$("#registration").submit(function(e){
$.ajax({
url: BASE_URL + 'auth/validateForm',
type: 'POST',
data: {
surname: $("#r-surname").val()
},
dataType: "json",
success: function(data) {
if(data.surname)
{
$('#error_surname').html(data.surname);
//prevent form submission
e.preventDefault();
}else{
$('#error_surname').html('');
//no errors, it will continue with form submission
}
},
error: function(data) {
e.preventDefault();
}
});
});
答案 2 :(得分:-1)
实际检查返回是空还是空。
success: function(data) {
if((data != null || data != "") && data.hasOwnProperty("surname"))
{
$('#error_surname').html(data.surname);
response = false;
}else{
$('#error_surname').html('');
response = true;
}