There are three things to keep in mind:
The browser can cache the JSON response, so we recommend adding a timestamp to the end of the URL so that the data is fresh. (This is true for the GET method, not necessarily the case with POST, though).
The content type of the JSON response must be " application / json " or " text / javascript ".
json_encode PHP 5.2, , , , , .
PHP 5.1.6, - , , , . " JSON", JSON, .
, / jQuery JSON . .
:
var now = new Date();
$.ajax({
type: "POST",
url: "page/post/" + now.valueOf().toString(),
data: {},
dataType: "json",
success: function (result) {
alert(result.message);
}
});
(/application/controllers/page.php):
class Page extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
}
function post($TimeStamp)
{
$data['json'] = '{"message":"The post was handled successfully."}';
$this->load->view('json_view', $data);
}
}
(/application/views/json_view.php):
<?php
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo $json;
?>