【问题标题】:CodeIgniter return data from controllerCodeIgniter 从控制器返回数据
【发布时间】:2012-08-29 14:18:09
【问题描述】:

我正在将 CodeIgniter 用于我正在进行的项目。

我在这样的视图中有一个 ajax 调用:

$.ajax({
    type: 'GET',
    url: 'extra/search/infojson/' + $(this).text().replace(/\s/g, "+");
    success: function(data) {
        /* Do something with that data */
    }

});

infojson 是控制器中的一个方法,它接受一个“用户名”参数,进行搜索,然后返回一个 JSON 对象。有什么方法可以返回这些数据而不必为其创建另一个视图?此方法将仅用于从这一页面返回此类数据,因此我不明白为什么我需要为此创建另一个视图。我读过关于 _output() 的文章,但对我来说没有任何意义。

【问题讨论】:

    标签: php ajax json codeigniter


    【解决方案1】:

    这就是答案:

    $this->config->set_item('compress_output', FALSE); 放在 echo 之前以禁用输出压缩。

    来源:http://codeigniter.com/forums/viewthread/155810/#784452

    【讨论】:

    • 我的答案的另一种方式:)
    • @Deepak:Steve 的 anwser 的优势在于,您可以默认启用压缩并在必要时禁用,而使用您的 anwser 意味着在任何地方都没有压缩。
    【解决方案2】:

    如果您在配置文件中压缩输出,请尝试设置$config[‘compress_output’] = FALSE;

    【讨论】:

      【解决方案3】:

      当然。

      使用PHP的json_encode()函数返回数据,在ajax请求时无需调用$this->load->view('someview', $data);将数据发送回浏览器。

      class Extra extends CI_Controller{
          function __construct(){
              parent::__construct();
          }
      
          function search($username){
              $results = your_search($username);
              echo json_encode(array("results" => $results));
          }
      }
      

      还有你的 jquery:

      $.ajax({
          type: 'GET',
          dataType: "json",
          url: 'extra/search/infojson/' + $(this).text().replace(/\s/g, "+");
          success: function(data) {
              if(data.results){
                  /* Do something with the results */
              }
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2012-02-21
        • 2011-08-04
        • 1970-01-01
        • 1970-01-01
        • 2011-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多