如何在codeigniter中将数据从控制器传递到jquery(Ajax)

时间:2014-05-21 07:37:46

标签: javascript php ajax codeigniter

控制器代码

$rates['poor'] = 10; 
$rates['fair'] = 20;

$this->load->view('search_result2', $rates);

//I have tried this in many ways but at least It executes the "success" in ajax file only with above way.  other ways I have tried ex :-
//$this->output->set_output(json_encode($rates));
//echo json_encode($rates);

我需要将此费率数组传递给ajax

js code

$.ajax({
    type:'POST',
    url:'some url',
    data:{'adID':adID},
    //dataType:'JSON', // when I uncommented this it displays nothing. when commented it displays "undefined" on the label below i have created
    success:function(rates){ 

        $('#rate_val').html('<label>'+rates.poor+'</label>');

        //I have tried this in many ways  ex :-
        // $('#rate_val').html('<label>'+rates['poor']+'</label>');
        // $('#rate_val').html('<label>'+rates[0]+'</label>');

    }
});

这会在标签上显示“undefined”。我无法获取从控制器传递的数据。请帮忙吗?

2 个答案:

答案 0 :(得分:0)

  1. 取消注释dataType:'JSON'
  2. 使用来自控制器
  3. echoset_output将输出设置为json
  4. 从ajax
  5. 获取rates.poorrates['poor']的项目

    <强>控制器

    public function post_url()
    {
        $rates = array();
        $rates['poor'] = 10; 
        $rates['fair'] = 20;
    
        $this->output->set_output(json_encode($rates));
    }
    

    <强>的Ajax

    <script>
    $.ajax({
        type:'POST',
        url:'POST_URL',
        data:{'adID':adID},
        dataType:'JSON',
        success:function(rates){ 
            $('#rate_val').html('<label>'+rates.poor+'</label>');
        }
    });
    </script>
    

答案 1 :(得分:0)

$data['a']='100';
$data['b']='200';
echo json_encode(array('success'=>$data));

jquery的

<script>
$.ajax({
    type:'POST',
    url:'POST_URL',
    data:{'adID':adID},
    dataType:'JSON',
    success:function(rates){
       var data     = jQuery.parseJSON('['+response+']');

        $('#rate_val').html('<label>'+data.succcess.a+'</label><label>'+data.succcess.b+'</label>');
    }
});
</script>

我相信它可以按你的意愿执行。