2014-01-19 52 views
0

我有一个jQuery问题,关于如何从我的codeigniter控制器获取数据到jQuery函数。获取json_encode从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是正确的方法。但是,任何解决方案都行.. :)

谢谢..

+0

AJAX是什么亚所需要的! – tymeJV

+0

@Zurreal:你是什么控制器?这个'$ id = $ this-> session-> userdata('userID');'可能是php代码。你使用的是PHP吗? – surfmuggle

+0

@threeFourOneSixOneThree:yeah..im使用PHP与COdeigniter框架..xD – Zurreal

回答

1

我觉得你的控制器不生产的有效的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); 
     } 
    } 
}); 
+0

哇..它真的工作..我觉得它有点辛苦一开始..但我得到它无论如何.. :)谢谢! – Zurreal

相关问题