Php 使用jQuery的Codeigniter中的Ajax
我有一个控制器叫Php 使用jQuery的Codeigniter中的Ajax,php,javascript,jquery,ajax,codeigniter,Php,Javascript,Jquery,Ajax,Codeigniter,我有一个控制器叫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 resp
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);
window.setInterval(函数(){
$.get('时间/索引',
//当Web服务器响应请求时
功能(时间){
$('#mydiv').html(time+'
');
}
)
}, 5000);
可以看出,只有html响应可以使用,但如果我希望时间控制器返回数组、对象甚至变量等,我该怎么做呢?您可以在服务器端使用
<?php
class Time extends CI_Controller
{
// just returns time
public function index()
{
echo json_encode(array('time'=>time());
}
}
?>
<?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());
}
}
?>
您可以在服务器端使用
<?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());
}
}
?>
您应该使用json_encode返回数组,例如:return json_encode($timeArray);,然后是ajax部分,您应该解码并迭代数组,因为您需要使用json_encode返回数组,例如:return json_encode($timeArray);,然后是ajax部分,您应该根据需要对数组进行解码和迭代
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);