2013-08-28 25 views
1

我有控制器稱爲Time的Ajax在笨使用jQuery

<?php 
class Time extends CI_Controller { 
    // just returns time 
    public function index() { 
    echo time(); 
    } 
} 
?> 

該控制器輸出的當前時間和由在視圖中使用以下代碼加載。

window.setInterval(function() { 
    $.get('time/index', 
    // when the Web server responds to the request 
    function(time) { 
     $('#mydiv').html(time+'<br/>'); 
    } 
) 
}, 5000); 

如可以看出只有HTML的響應只能使用,但如果我想Time控制器返回數組,對象甚至是一個變量等我該怎麼辦呢?

+1

你應該使用json_encode,前返回數組:返回json_encode($ timeArray);,然後ajax的部分,你應該解碼和遍歷數組,只要你想 –

回答

2

您可以在服務器端使用json-encode function

<?php 
class Time extends CI_Controller { 
    public function index() { 
    // encode the what ever value (array, string, object, etc) 
    // to json string format 
    echo json_encode(time()); 
    } 
} 
?> 

並在javascript上解析JSON與JSON.parse。你也可以使用$.parseJSON

window.setInterval(function() { 
    $.get('time/index', 
    // when the Web server responds to the request 
    function(returnedValue) { 
     // parse json string to json object 
     // and do object or varible manipulation 
     var object = JSON.parse(returnedValue); 
    } 
) 
}, 5000); 
2
<?php 

class Time extends CI_Controller 
{ 
    // just returns time 
    public function index() 
    { 
    echo json_encode(array('time'=>time()); 
    } 
} 

?> 

,並在您的視圖

window.setInterval(
function() 
{ 

$.get('time/index', 

     // when the Web server responds to the request 
     function(data) 
     { 
      $('#mydiv').html(data['time']+'<br/>'); 
     },"JSON" 
     ) 
} 
,5000);