我有一个启用和禁用按钮。单击时,每个按钮都会在控制台中返回一条“成功”消息。单击启用按钮即可工作,但是,需要单击禁用按钮两次才能在我的开发人员工具的控制台中打印“成功”消息。这有什么问题吗?有人可以帮我解决这个问题吗?多谢。这是我的代码:
<button class="btn_mode" value="1">Enable</button>
<button class="btn_mode" value="0">Disable</button>
<script type="text/javascript">
$(".btn_mode").click(function(){
var mode_val = $(this).val();
var postdata={'mode':mode_val};
$.ajax({
type:"POST",
url:"<?php echo base_url();?>superadmin/change_mode",
dataType:'json',
data:postdata,
success: function(data){
if(data.notify=="Success")
{
console.log(data.notify);
location.reload();
}
else{
console.log(data.notify);
}
}
});
});
</script>
我的 Controller 功能
function change_mode(){
$mode = $this->input->post('mode');
$query = $this->course_booking_model->change_mode($mode);
if($query){
$notification = "Success";
}
else{
$notification = "Failed";
}
echo json_encode(array('notify'=>$notification));
}
型号
function change_mode($mode){
$id = 1;
$data = array('mode' => $mode);
$this->db->where('id',$id);
$this->db->update('maintenance_mode',$data);
return true;
}
在 javascript 中添加 console.log('Posting mode_val: ' + mode_val);
时的输出
单击控制台中的启用按钮输出
单击禁用按钮时在控制台中输出
最佳答案
由于您的事件连接看起来很好,我怀疑服务器端出了问题,这意味着您的成功处理程序没有触发。尝试在 ajax 调用之前记录日志,看看是否会触发点击事件:
$(".btn_mode").click(function(){
var mode_val = $(this).val();
var postdata={'mode':mode_val};
console.log('Posting mode_val: ' + mode_val);
$.ajax({
type:"POST",
url:"<?php echo base_url();?>superadmin/change_mode",
dataType:'json',
data:postdata,
success: function(data){
if(data.notify=="Success")
{
console.log(data.notify);
location.reload();
}
else{
console.log(data.notify);
}
}
});
});
如果上面在您单击按钮时记录了预期值,则意味着您的 php 脚本在您第一次使用 mode_val = 0
调用时失败。
您可以 try catch 可能抛出的任何异常,如下所示:
function change_mode(){
try{
$mode = $this->input->post('mode');
$query = $this->course_booking_model->change_mode($mode);
if($query){
$notification = "Success";
}
else{
$notification = "Failed";
}
}
catch(Exception $e){
$notification = $e->getMessage();
}
echo json_encode(array('notify'=>$notification));
}
编辑: 您上传的图像表明服务器端代码存在问题,并且您的按钮单击正常。如果您更新 php 以捕获错误并返回它,您应该能够得到有关出了什么问题的提示。要查看调用完成,您可以实现“完成”和/或“错误”回调:
$.ajax({
type:"POST",
url:"<?php echo base_url();?>superadmin/change_mode",
dataType:'json',
data:postdata,
success: function(data){
if(data.notify=="Success")
{
console.log(data.notify);
location.reload();
}
else{
console.log(data.notify);
}
},
error: function(jqXhr, txtStatus, errThrown){
console.log('Call failed with status:' + txtStatus);
if(errThrown)
console.log('and error:' + errThrown);
},
complete: function(jqXhr, txtStatus){
console.log('Call completed with status:' + txtStatus);
}
});
});
关于javascript - 按钮需要点击两次才能工作,我希望只点击一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19543105/