如何在Codeigniter中将数据从控制器传递到jquery(Ajax) [英] how to pass data from controller to jquery (Ajax) in codeigniter

查看:59
本文介绍了如何在Codeigniter中将数据从控制器传递到jquery(Ajax)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

控制器代码

$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

i need to pass this rates array to ajax

js代码

$.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>');

    }
});

这将在标签上显示未定义。我无法获取从控制器传递来的数据。请帮忙吗?

this displays "undefined" on label. I can't get the data I have passed from controller. please help ?

推荐答案


  1. 取消注释 dataType:'JSON'

  2. 使用 echo set_output 将输出设置为json控制器

  3. 使用 rates.poor rates ['poor'] 来自ajax

  1. Uncomment dataType:'JSON'
  2. Set output as json with echo or set_output from controller
  3. Get item with rates.poor or rates['poor'] from ajax

控制器

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>

这篇关于如何在Codeigniter中将数据从控制器传递到jquery(Ajax)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆