我尝试使用ajax从codeigniter控制器方法进行geta响应,但它不起作用,响应是空的。
<script type="text/javascript">
$(document).ready(function(){
$("#crear").click(function() {
//$('#error_msg').html("Error");
$.ajax({
type:"POST",
url:"clase/create",
success:function(data){
$('#error_msg').html(data);
}
});
});
});
</script>
这是控制器
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Clase extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('clase_model','',TRUE);
$this->load->helper(array('form'));
}
function index()
{
if($this->session->userdata('logged_in')){
$data['title'] = 'Gestión de Clases';
$data['clases'] = $this->clase_model->getAll();
$this->load->view('header', $data);
$this->load->view('clase_view', $data);
}
else{
redirect('login', 'refresh');
}
}
function create(){
if($this->session->userdata('logged_in')){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Nombre', 'trim|min_length[2]|required');
$this->form_validation->set_rules('info', 'Información', 'trim');
if($this->form_validation->run() == FALSE){
$data = array(
'error_message1' => form_error('name'),
'error_message2' => form_error('info')
);
return $data['error_message1'];
}
else{
if($this->input->post('info')){
$this->insert2($this->input->post('name'),$this->input->post('info'));
}
else{
$this->insert1($this->input->post('name'));
}
}
}
else{
redirect('login', 'refresh');
}
}
function insert2($name,$information){
$dat = array(
'nombre'=>$name,
'info'=>$information
);
$this-> db ->insert('clase',$dat);
echo $name;
redirect('clase', 'refresh');
}
function insert1($name){
$dat = array(
'nombre'=>$name,
);
$this-> db ->insert('clase',$dat);
redirect('clase', 'refresh');
}
}
?>
和响应标题
Cache-Control
no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection
Keep-Alive
Content-Length
0
Content-Type
text/html; charset=UTF-8
Date
Sat, 25 Apr 2015 16:04:47 GMT
Expires
Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive
timeout=5, max=100
Pragma
no-cache
Server
Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3
Set-Cookie
ci_session=941a601d7eaf9f590d21bd4c0aa8c2ac043faa81; expires=Sat, 25-Apr-2015 18:04:47 GMT; Max-Age=7200
; path=/; httponly
x-powered-by
PHP/5.6.3
有人可以告诉我出了什么问题吗?这是我第一次使用ajax
答案 0 :(得分:2)
要在codeigniter中的ajax请求中进行响应,您应该使用 -
echo json_encode('your data');