簡體   English   中英

如何在Codeigniter中將數據從控制器傳遞到jquery(Ajax)

[英]how to pass data from controller to jquery (Ajax) in 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代碼

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

    }
});

這會在標簽上顯示“未定義”。 我無法獲取從控制器傳遞來的數據。 請幫忙 ?

  1. 取消注釋dataType:'JSON'
  2. 使用控制器的echoset_output將輸出設置為json
  3. 從ajax獲取帶有rates.poorrates['poor']

調節器

public function post_url()
{
    $rates = array();
    $rates['poor'] = 10; 
    $rates['fair'] = 20;

    $this->output->set_output(json_encode($rates));
}

阿賈克斯

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

我相信它可以按您的意願執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM