我有一个带有ajax的插入功能,现在,当我成功插入一个值时,我想通过ajax重定向页面。
这是我的 Controller :
public function create(){
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
$this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');
if($this->form_validation->run($this) == FALSE){
foreach ($_POST as $key => $value) {
# code...
$data['messages'][$key] = form_error($key);
}
}else{
$data['success'] = true;
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
$this->index;
}
echo json_encode($data);
}
这是我的 JavaScript:
<script>
$('#form-user').submit(function(e){
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax({
url: me.attr('action'),
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response){
if (response.success == true) {
// if success we would show message
// and also remove the error class
$('#the-message').append('<div class="alert alert-success">' +
'<span class="glyphicon glyphicon-ok"></span>' +
' Data has been saved' +
'</div>');
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
}else{
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value)
});
}
}
});
});
</script>
此操作已成功保存数据,但未重定向到另一页面。
我是 ajax 新手,我想了解如何在不加载模板的情况下将其重定向到我的页面。
添加 - 模型
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
最佳答案
使用
if (response.success == true) {
// no extra code
// url where you want to redirect
location.href = "<?php echo base_url('class/function'); ?>";
}
在你的成功函数中
关于javascript - Codeigniter ajax插入成功重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37785242/