【发布时间】:2020-03-16 04:44:16
【问题描述】:
我正在使用 ajax 进行操作 Create 和 Update
我已经可以创建和更新了,但是如果我按或按Enter键然后从另一个页面显示,这有点不好看,并且在点击Enter 键。
{"success":false,"type":"update"}
对于视觉表示,这里是在输入字段上按Enter键后的样子
这就是我在视图中输入的内容
<input type="text" name="group[]" id="group" placeholder="Enter your Choice" class="form-control" />
在我的控制器中
public function addGroup(){
$result = $this->group_model->addGroup();
$msg['success'] = false;
$msg['type'] = 'add';
if($result){
$msg['success'] = true;
}
echo json_encode($msg);
}
public function updateGroup(){
$result = $this->group_model->updateGroup();
$msg['success'] = false;
$msg['type'] = 'update';
if($result){
$msg['success'] = true;
}
echo json_encode($msg);
}
在模型中
public function updateGroup(){
$id = $this->input->post('txtId');
$field = array(
'group_name'=>$this->input->post('group')
);
$this->db->where('id', $id);
$this->db->update('groups', $field);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
public function addGroup(){
$field = array(
'group_name'=>$this->input->post('group'),
);
$this->db->insert('groups', $field);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
阿贾克斯
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var group = document.getElementById('group').value;
if(group.replace(/\s/g, "").length <=0 ) {
swal("Submission fail!", "Enter the required field", "error");
return false;
}
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type = 'updated'
}
swal("Success!", "You delete a Question!", "success");
showGroups();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
});
【问题讨论】:
-
你的 ajax 代码在哪里也显示了 ..
-
@BoominathanElango - 更新了我上面的代码,你可以在底部看到它。谢谢!
-
问题是你可以禁用回车键直到你得到正确的响应?
标签: javascript php json ajax codeigniter