开发者

Returning a json object in codeigniter(flashdata)

How does one go about returning a json object in this case(messages) to a view(admincp_index). The method below works fine but I would really like to spice it up with some animations

Regards, Phil

/* AdmincontrolPanel */
function index()
{
    $data['messages'] = $this->session->flashdata('messages');
    $data['content'] = 'admincp/admincp_index';
    $this->load->view('backend/template', $data);
}


 function applicant()
 {
      $id = $this->input->post('id');

      if($this->input->post('accept'))
      {
            if($this->admincpModel->accept_applicant($id) == TRUE)
            {
                 $this->session->set_flashdata('messages', '<div class="开发者_StackOverflow社区ok">Applicant Added!</div>');
                 redirect('admincp');
            }            
 }

/* admincp_index */

if($messages){
    // echo messages
}


use code igniter 's output class to response json.

$this->output
    ->set_content_type('application/json')
    ->set_output(json_encode(array('foo' => 'bar')));


There are three things that need to be kept in mind:

  1. The browser may cache the JSON response, so it's a good idea to append a time-stamp to the end of the URL to keep the data coming in fresh. (This is true of the GET method, not necessarily so with POST though).

  2. The content type of the JSON response needs to be "application/json" or "text/javascript".

  3. The json_encode function was included with PHP 5.2, so older environments may not be able to use it, and you'll have to either get the module installed or write your own encoding class.

I'm doing some work on a server running PHP 5.1.6, and I don't need to serialize any complex types, so I've found the technique shown below to work fine. I'm using a simple "JSON view" which sets the correct content type in the response header, and emits a JSON string which was manually concatenated in the controller.

Phil, jQuery effects/animations could make use of the returned JSON data in the success callback function. In the example below I'm just showing message in an alert box.

Client-side Code:

// the jQuery POST URL includes a time stamp
var now = new Date();
$.ajax({
    type: "POST",
    url: "page/post/" + now.valueOf().toString(),
    data: {},
    dataType: "json",
    success: function (result) {
        alert(result.message);
    }
});

Controller (/application/controllers/page.php):

class Page extends CI_Controller {

    function __construct()
    {
        parent::__construct();
    }

    function index()
    {
    }

    function post($TimeStamp)
    {
        /* process request... $Timestamp may or may not be used here. */

        $data['json'] = '{"message":"The post was handled successfully."}';
        $this->load->view('json_view', $data);
    }
}

View (/application/views/json_view.php):

<?php
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo $json;
?>


You doing wrong way. If you want to get json object, AJAX is the best way to handle this. In your admincp_index view (with jquery)

$.ajax({
        type: 'POST',
        url: 'controller/applicant',
        data: 'your post data',
        success: function(response) {
            var response = $.evalJSON(r);
            if(response.message) {
               //do some animation
            }
        }
    });

applicant method

function applicant()
{
  $id = $this->input->post('id');
  if($this->input->post('accept'))
  {
        if($this->admincpModel->accept_applicant($id) == TRUE)
        {
             echo json_encode(array('message'=>'<div class="ok">Applicant Added!</div>'));
             exit();
        }         
   }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜