开发者

jQuery and CodeIgniter AJAX with JSON not working

开发者 https://www.devze.com 2022-12-25 01:39 出处:网络
I trying to make my first AJAX with JSON call using jQuery and CodeIgniter. But for some weird reason it\'s not working.

I trying to make my first AJAX with JSON call using jQuery and CodeIgniter. But for some weird reason it's not working.

The jQuery code:

var item = "COOL!";
$.post("http://192.168.8.138/index.php/main/test", { "item" : item },
         function(data){
            alert(data.result);
         }, "json");

The CodeIgniter code:开发者_如何学Python

<?php
class main extends Controller {
   function test() {
      $item = trim($this->input->post('item'));
      $array = array('result' => $item);
      echo json_encode($array);
   }
}
?>

I tried to access the http://192.168.8.138/index.php/main/test page manually and it seems to be working, I got: {"result":""}

I also tried to use Firebug to see XMLHttpRequest but saw nothing.

I have no idea what am I doing wrong... Need help really badly. Thank you.


You may need to set the HTTP content type to application/json to get this to work:

<?php
class main extends Controller {
   function test() {
      $item = trim($this->input->post('item'));
      $array = array('result' => $item);
      header('Content-Type: application/json',true);
      echo json_encode($array);
   }
}
?>)
0

精彩评论

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