【问题标题】:AJAX AND JSON within CodeigniterCodeigniter 中的 AJAX 和 JSON
【发布时间】:2010-12-24 04:44:51
【问题描述】:

我有一个网站,我想通过 AJAX 和 JSON 获得一些查询结果,但我完全不知道该怎么做,我有这个功能,

public function category() {
        $table = $this->uri->segment(2);
        $content_id = $this->uri->segment(3);
        $data['content'] = $this->site_model->get_content($table, $content_id);
        $this->load->view('template/right-content', $data);
    }

本质上,运行的查询是动态的,具体取决于传递的 url,我需要的是,因为用户单击类似的链接

<a href="/category/blog/1" id="blog">Read the blog</a>

从这个链接我得到博客和 1 传递给查询,但我需要将结果加载到加载到我的主模板中的视图中,然后每次单击链接时执行相同的操作而不覆盖以前的数据,有谁知道如何做到这一点?

【问题讨论】:

    标签: php jquery ajax json codeigniter


    【解决方案1】:

    如果我理解正确,您需要向该 url 发送 Ajax 请求,然后将其附加到文档中的适当位置。像这样的:

    $("#blog").click(function () {
        var url = $(this).attr("href");
        $.ajax ({
            url: url,
            type: "POST",
            success : function (html) {
                $("#someDiv").append(html);
            }
        });
    });
    

    所以 Codeigniter 视图应该只包含内容,实际上,也许还有一些必要的标记来设置它的样式。内容所在的容器应该已经在链接所在的页面中。

    【讨论】:

      【解决方案2】:

      或者,如果您真的希望您的数据以 JSON 形式返回,您可以这样做

      public function category() {
              $table = $this->uri->segment(2);
              $content_id = $this->uri->segment(3);
              echo json_encode($this->site_model->get_content($table, $content_id));
      
      }
      

      并且,如果您使用上述作者使用 $.append 的方法,您可能希望这样修改您的控制器:

      public function category() {
              $table = $this->uri->segment(2);
              $content_id = $this->uri->segment(3);
              $data['content'] = $this->site_model->get_content($table, $content_id);
              echo $this->load->view('template/right-content', $data, TRUE);
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-18
        • 2014-06-01
        • 1970-01-01
        • 2017-06-19
        • 2013-07-28
        相关资源
        最近更新 更多