2014-01-19 68 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

相關問題