gpt4 book ai didi

jquery - ajax成功函数中的条件语句

转载 作者:行者123 更新时间:2023-12-01 01:18:09 24 4
gpt4 key购买 nike

我正在使用 Codeigniter MVC 框架,但我正在努力使用 Jquery Ajax。我的问题是如何将条件语句放入 ajax 成功函数中?

基本上我想要做的是成功输入后,它将重定向到另一个页面,否则将显示错误:手机号码不匹配或如果为空请填写空白。

Controller 方法

if($mobile_number == "") {
$data = array('message' => "Please fill up the blanks", 'success' => 'no');

}
elseif($mobile_number != "123") {
$data = array('message' => "Please does not match", 'success' => 'no');

}else {
#redirect('home/test');
$data = array('message' => "Mobile match.", 'success' => 'yes');
}
$output = json_encode($data);
echo $output;

my_ajax.js

$(document).ready(function(){


$("#request_submit").click(

function(){

var mobtel=$("#mobtel").val();

$.ajax({
type: "POST",
url: "post_action",
dataType: "json",
data: "mob_tel="+mobtel,
cache:false,
success: function (data) {

if(data.success == 'yes') {
$("#form_message").html(data.message).fadeIn('slow');
}
else if(data.success == 'no') {
alert('error');
}
}

});
});
});

提前致谢。希望有人可以在这里帮助我。 (T_T)

最佳答案

不确定我是否很好地理解了你的问题...从我得到的情况来看,这应该会插入到正确的方向。

如果我是您,我会将回复更改为以下格式:

$data = array(
'message'=> /* Your message */,
'success' => /* True or false */,
'case'=> /* 1,2,3 something unique to tell the cases apart */,);

echo json_encode($data);

所以,在 jQuery 中我可以简单地这样做:

 $.ajax({
type: "POST",
url: "post_action",
dataType: "json",
data: "mob_tel="+mobtel,
cache:false,
success: function (data) {

switch(data.case){
1: /*First case */
break;
2: /*Second... */
break;
3: /* You know the drill... */
break;
default:
/* If none of the above */

}
}

});

由于您的代码中有三种情况,因此最佳实践是将它们作为三种情况进行处理。代码更可靠,更不容易出错。

希望这会有所帮助!

关于jquery - ajax成功函数中的条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9063300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com