通过ajax将数组传递给控制器

时间:2014-01-15 19:05:05

标签: ajax codeigniter post

所以我使用AJAX将数组发送到控制器

AJAX

 $('#concept').click(function(){

                       $.ajax({
                              url: 'http://localhost:8888/index.php/trial/getValues',
                              type:'POST',
                              dataType: 'json',
                              data: course,
                              error: function(){
                              $('#testing1').append('<p>goodbye world</p>');
                              },
                              success: function(result) {
                              var htmlStr = '';
                              $.each(result, function(a, b){
                                     htmlStr += b.qText + '<br />';
                                     });
                              alert("YEAH YOU WAS SUCCESSFUL");
                              $('#testing1').append(htmlStr);
                              } // End of success function of ajax form
                              }); // End of ajax call

当然是一个包含两个字符串的javascript数组。

控制器

function getValues(){
    $playlist = $this->input->post('course');
    $this->load->model('get_db');
    $data = $this->get_db->getAll($playlist);//$var inside ()
    $this->output->set_content_type('application/json');
    $this->output->set_output(json_encode($data));
    return $data;
}

模型

class Get_db extends CI_Model{
    function getAll($pList){
        $query=$this->db->query("SELECT * FROM questions WHERE playlistID= '$pList[0]' OR playlistID='$pList[1]'");
        return $query->result();

    }
}

我已经完成了硬编码,可以确认控制器和模型功能是否正常工作。问题在于我认为ajax中的'data'参数。我只是不相信数据以正确的方式传递给控制器​​。我无休止地搜索其他问题,我知道有类似的问题,但我在这种情况下找不到解决方案。

提前感谢您提供的任何信息:)

1 个答案:

答案 0 :(得分:0)

您必须echo控制器中的JSON编码数据,而不是返回它。在Ajax回调中,您必须在JSON.parse()调用之前result $.each(..)

<强>控制器

function getValues(){
    $playlist = $this->input->post('course');
    $this->load->model('get_db');
    $data = $this->get_db->getAll($playlist);//$var inside ()
    echo json_encode($data);
    // $this->output->set_content_type('application/json');
    // $this->output->set_output(json_encode($data));
    // return $data;
}

<强> Ajax的呼叫

$.ajax({
    url: 'http://localhost:8888/index.php/trial/getValues',
    type:'POST',
    dataType: 'json',
    data: course,
    error: function(){
        $('#testing1').append('<p>goodbye world</p>');
    },
    success: function(result) {
        var htmlStr = '';
        var jsonData = JSON.parse(result);
        $.each(jsonData, function(a, b){
            htmlStr += b.qText + '<br />';
        });
        alert("YEAH YOU WAS SUCCESSFUL");
        $('#testing1').append(htmlStr);
    }
相关问题