2017-03-04 47 views
0

我是codeigniter的新手,这是我第一次使用jquery ajax。CodeIgniter上的JQuery AJAX:返回null的JSON数据类型

我有一个模式表单,将信息传递给视图上的脚本。我的问题是,阿贾克斯是空值...
我试图提醒脚本上的数据,它显示正确的值,但是当它将数据作为JSON传递给控制器​​时,我认为这是失败的地方。我不知道该怎么办。你有什么主意吗?在视图

$(function() { //add new user from modal 
    $('#adduser_modal').modal('show'); 
    $('#adduser_modal').find('.modal-title').text('Add New User'); 
    $('#addUser_form').attr('action', '<?php echo base_url() ?>Hgv_controller/addnewuser'); 
}); 
$('#saveuser_btn').click(function() { 
    var url = $('#addUser_form').attr('action'); 
    $.ajax({ 
     type: 'ajax', 
     method: 'post', 
     url: url, 
     data: data, 
     async: false, 
     dataType: 'json', 
     jsonpcallback: success 
    : 
    function (response) { 
     if (response.success) { 
      $('#adduser_modal').modal('hide'); 
      $('#addUser_form')[0].reset(); 
     } 
    } 
}); 

这里

片断脚本的代码片段从控制器

public function addnewuser() 
{ 
    $this->load->database(); 
    //load model for crud 
    $this->load->model('Crud'); 
    $result = $this->Crud->adduser(); 

    $msg['success'] = false; 
    $msg['type'] = 'add'; 
    if ($result) { 
     $msg['success'] = true; 
    } 
    echo json_encode($msg); 
} 

,这里是从模型

使用 jsonpcallback
public function adduser() 
{ 
    $field = array(
     'username' => $this->input->post('hgv_username'), 
     'f_name' => $this->input->post('hgv_firstname'), 
     'l_name' => $this->input->post('hgv_lastname'), 
     'password' => $this->input->post('hgv_password'), 
     'user_type' => $this->input->post('hgv_type'), 
    ); 
    $this->db->insert('hgv_user', $field); 
    if ($this->db->affected_rows() > 0) { 
     return true; 
    } else { 
     return false; 
    } 
} 
+0

您是否试图转储或打印您在模型中获得的发布数据?验证 –

+0

或尝试print_r($ this-> input-> post());出口;在您的控制器中加载您的模型以查看您是否在控制器中获取数据 –

+0

1.'ajax'不是有效的http请求方法('type:'ajax''),2.'type'是别名对于'method',3.'async:false'使请求同步并阻止脚本/ UI,4. $ .ajax(...)'选项对象有语法错误(不必要的'jsonpcallback'属性) – Andreas

回答

0

片段似乎不合适。试试这个

$('#saveuser_btn').click(function() { 
    var url = $('#addUser_form').attr('action'); 
    $.ajax({ 
     method: 'post', 
     url: url, 
     data: data, 
     dataType: 'json', 
     success: function (response) { 
     if (response.success) { 
      $('#adduser_modal').modal('hide'); 
      $('#addUser_form')[0].reset(); 
     } else { 
      alert('New User was not added.'); 
     } 
    } 

我也删除了一些你可能不应该使用的ajax选项。 其余的代码看起来不错,但是通过使用它你可以使你的控制器效率更高一点。

public function addnewuser() 
{ 
    $this->load->database(); 
    //load model for crud 
    $this->load->model('Crud'); 
    $msg['success'] = $this->Crud->adduser(); 
    $msg['type'] = 'add'; 
    echo json_encode($msg); 
} 

你的模型已经返回TRUEFALSE所以直接把那回报$msg阵列英寸

+0

谢谢,但我仍然得到相同的结果;它仍然以空值输入数据库。 –

+0

如何以及在哪里设置var'data'的值? – DFriend