jQuery和codeIgniter Ajax和JSON不工作

问题描述:

我试图让我的第一个Ajax和JSON调用使用jQuery和codeIgniter。 但对于一些奇怪的原因,它不工作。

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

jQuery的code:

The jQuery code:

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

在codeIgniter code:

The CodeIgniter code:

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

我试图手动访问 http://192.168.8.138/index.php/main/test 页,它似乎是工作,我得到了: {结果:}

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":""}

我还试图用萤火虫来看看 XMLHtt prequest 什么也没看见。

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.

您可能需要设置HTTP内容类型设置为应用程序/ JSON 来得到这个工作:

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);
   }
}
?>)