【问题标题】:jQuery and CodeIgniter AJAX with JSON not working带有 JSON 的 jQuery 和 CodeIgniter AJAX 不起作用
【发布时间】:2010-03-27 23:08:35
【问题描述】:

我尝试使用 jQuery 和 CodeIgniter 使用 JSON 调用创建我的第一个 AJAX。 但由于某些奇怪的原因,它不起作用。

jQuery 代码:

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

CodeIgniter 代码:

<?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 页面,它似乎工作正常,我得到:{"result":""}

我也尝试使用 Firebug 查看XMLHttpRequest,但什么也没看到。

我不知道我做错了什么...非常需要帮助。 谢谢。

【问题讨论】:

    标签: jquery ajax json codeigniter


    【解决方案1】:

    您可能需要将 HTTP 内容类型设置为 application/json 才能使其工作:

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

    【讨论】:

    • 你能给我看一个使用application/json类型的完整例子吗?谢谢。
    • 很抱歉,这一切对我来说都是新事物,我该把它放在哪里? CodeIgniter 还是 jQuery 页面端?再次感谢。
    • 您的 AJAX 请求是从同一 Web 服务器上的另一个页面发出的吗?为什么要使用绝对“路径”(IE,带有 192.168.8.138)而不是相对“路径”(例如 index.php/main/test)?
    • 这可能是你的问题。只有当您向页面所属的同一域发出请求时,AJAX 才会起作用。所以...把你的测试页面放在同一个服务器上(你可以暂时把它和 index.php 放在同一个目录中)并重新测试。
    • 就像贾斯汀说的 - 上面有 javascript 的请求页面必须与 CI 安装在同一台服务器上 - 换句话说,您可以(通过 AJAX)从另一个控制器调用视图,但请求页面和服务页面都需要在同一台服务器上。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多