【发布时间】:2017-02-04 06:01:15
【问题描述】:
我是 CodeIgniter 的新手,我在使用 AJAX 更新我的 MySQL-DB 字段时遇到问题。 AJAX 代码没有更新数据库,当然,它没有使用json_encode 提供success 属性(我对名称感到困惑)。
我已经尝试了很多次,当我不使用模型时——我将查询移动到直接在控制器中执行——它工作正常,数据库被更新了。但我认为这是个坏主意。
这是我的控制器的功能:
public function applicant_is_present(){
$data = array(
'idplm'=>$this->input->post('idplm')
);
$this->applicant_model->give_attendance($data);
echo json_encode(array("status" => TRUE));
}
这是我的模型函数:
function give_attendance($applicant){
$query = 'UPDATE apptable SET khdrp = \'present\' WHERE idplm = '.$applicant->idplm.' ';
$this->db->query($query);
}
这是我的看法:
<!DOCTYPE html>
<link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap.css"); ?>" />
<html>
<head>
<script type="text/javascript" src="<?php echo base_url("assets/js/jquery-3.1.1.js"); ?>"></script>
<script type="text/javascript" src="<?php echo base_url("assets/js/bootstrap.js"); ?>"></script>
<script type="text/javascript">
function attends(id){
var url;
url = "<?php echo site_url('applicant/applicant_is_present')?>";
$.ajax({
url : url,
type: "POST",
data: {idplm: id},
dataType: "JSON",
success: function(data){
if(data.status){
jQuery("div#beginning_response").show();
}else{
for (var i = 0; i < data.inputerror.length; i++){
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); $('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]);
}
}
},
error: function (jqXHR, textStatus, errorThrown){
alert('Error adding / update data');
}
});
}
</script>
</head>
<body>
.
.
//some codes to print $that_applicant object
.
.
<div id = "beginning_response" style='display: none'>
Present!
</div>
Applicant's Presence :
//this is the button to call the script
<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="update" onclick="attends('<?php echo $that_applicant->idplm; ?>')">Present</a>
<br/>
<br/>
【问题讨论】:
-
尝试不使用
$this->applicant_model->give_attendance($data);这一行并检查你是否获得了ajax succss。 -
是的,我得到了ajax成功,但是没有这条线,我如何更新数据库?
-
您的代码有误。您应该打开错误以查看您遇到了什么错误。您将
$data作为数组发送到give_attendance函数,但您将其用作对象$applicant->idplm。它给你错误。将其用作$applicant['idplm']
标签: mysql ajax codeigniter