从codeigniter控制器获取json_encode到jquery

时间:2014-01-19 02:30:46

标签: php jquery codeigniter

我在jQuery中有一个问题,关于如何从我的codeigniter控制器获取数据到jQuery函数。

我在jQuery中有一个进度条,我需要进度条的值取决于控制器的输出;我在控制器中使用 json_encode

Jquery的

$(function() {
  $( "#progressbar" ).progressbar({
  value: //get value from the controller json_encode
      });
  });

控制器

public function countScoreCh(){
$id = $this->session->userdata('userID');
$data['getScore'] = $this->lawmodel->battleUserID($id);
foreach($data['getScore'] as $row){
    $scoreCH = $row->challengerScore;
    echo json_encode(
    array(
    'scoreCH' => $scoreCH,
            )
        );
}

}

进度条功能将是这样的。

$(function() {
  $( "#progressbar" ).progressbar({
  value:   //jsn.scoreCH value
      });
  });

有可能这样做吗?我不知道使用json_encode是否正确。但任何解决方案都会...... ..)

谢谢..

1 个答案:

答案 0 :(得分:3)

我认为你的控制器不会产生有效的json。因为它会像这样产生一个json字符串:

{scoreCH:<SomeValue>}{ScoreCH:<SomeValue>}{ScoreCH:<Somevalue>}

如果你把一组ScoreCH值放在一些“json包装器”中会更好,所以你应该修改你的控制器来创建一个临时变量,它包含模型中的所有值,如下所示:

public function countScoreCh(){
    $id = $this->session->userdata('userID');
    $data['getScore'] = $this->lawmodel->battleUserID($id);
    // Here is "my hack"
    $output = array(); // it will wrap all of your value
    foreach($data['getScore'] as $row){
          unset($temp); // Release the contained value of the variable from the last loop
          $temp = array();

          // It guess your client side will need the id to extract, and distinguish the ScoreCH data
          $temp['id_of_ScoreCH'] = $row->id;
          $temp['ScoreCH'] = $row->ScoreCH;

          array_push($output,$temp);
    }
    // Now the $output supposed to be a two dimensional array looks like this one
    // array(
    //    [0]=>array("id_of_ScoreCH"=>SomeID,"ScoreCH"=>SomeValue),
    //    [1]=>array("id_of_ScoreCH"=>SomeID,"ScoreCH"=>SomeValue),
    //    [2]=>array("id_of_ScoreCH"=>SomeID,"ScoreCH"=>SomeValue)
    //   );

    // Then emit the wrapped value It would produce array of object JSON
    // Dont forget to put the header format
    header('Access-Control-Allow-Origin: *');
    header("Content-Type: application/json");
    echo json_encode($output);
 }

接下来在您的客户端(HTML)上使用JSON.parse(<string_retrieved_from_controller>),就像这样:

$.ajax({
    url:<your_controller_name/you_method_name>,
    data: <your_specific_data_you_want_to_pass_to_the_server>,
    method:<post/get>
    success:function(retrieved_data){
         // Your code here.. use something like this
         var Obj = JSON.parse(retrieved_data)

         // Since your controller produce array of object you can access the value by using this one :
         for(var a=0; a< Obj.length; a++){
              alert("the value with id : " + Obj.id_of_scoreCH + "is " + Obj.ScoreCH);
         }
    }
});