[英]Ajax in Codeigniter using jQuery
我有一个叫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
控制器返回数组,对象甚至变量等怎么办呢?
<?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);
您可以在服务器端使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.