1

コントローラーを呼び出しましたTime

<?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コントローラーに配列、オブジェクト、または変数などを返すようにするにはどうすればよいですか?

4

2 に答える 2

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);
于 2013-08-28T05:37:42.293 に答える
2

サーバー側でjson-encode関数を使用できます。

<?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.parse を使用して json を解析します。$.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);
于 2013-08-28T05:44:59.343 に答える