【问题标题】:jQuery not properly loading a CodeIgniter viewjQuery 没有正确加载 CodeIgniter 视图
【发布时间】:2012-01-05 18:39:21
【问题描述】:
$("#slideshow").click(function() {
    $("#content").fadeOut(function() {
        $(this).load('<?php $this->load->view("slideshow"); ?>', function() {
            $(this).fadeIn()
        });
    });
});

当我在 Ci 中运行上述代码时,CodeIgniter 将“幻灯片”视图挂在文档的开头。我需要它仅在单击“幻灯片放映”的 ID 时显示。这段代码 sn-p 通常有效,但不知道为什么它现在表现得很有趣。有什么想法吗?

【问题讨论】:

  • 你到底在做什么? slideshow 视图中有什么?
  • .load() 的第一个参数应该是一个 URL,而不是 HTML 或您的视图中的任何内容。

标签: php jquery codeigniter


【解决方案1】:

我不确定你想在这里做什么。 CodeIgniter 中的视图文件应该包含 HTML。控制器可以加载视图,并在需要时向它们传递数据。视图是模板。

$(this).load('<div id="test"></div>', function(){});

这将引发错误,因为 .load 需要一个 URL,而不是 HTML(除非您绑定到 onload 事件,其中第一个参数可以是一个数据数组,但我不认为那是你在做什么)。

我假设您想要的是让 jQuery 将视图文件的内容加载到 #content 中。为此,您需要一个输出视图的控制器。例如:

控制器

function slideshow(){
    $this->load->view('slideshow');
}

jQuery:

$("#slideshow").click(function() {
   $("#content").fadeOut(function() {
      $(this).load('/path/to/controller/slideshow', function() {
         $(this).fadeIn()
      });
   });
});

【讨论】:

  • @MichaelGrigsby:没问题,很高兴我能帮上忙 :-)
【解决方案2】:

这会产生这样的垃圾,以至于您的浏览器会将其放在某处(在文档的开头):

$(this).load('<?php $this->load->view("slideshow"); ?>', function() {

因为字符串需要适当的编码,例如作为带有json_encode­Docs的javascript字符串:

$(this).html(<?php echo json_encode($view_html); ?>);
$(this).fadeIn(); 

检查CI docs how you get the view returned as string 而不是被输出。我把它留作练习。

【讨论】:

  • @Rocket:出错了?不知道,但是我修复了 URL。可能这需要第二个json_encode
  • $(this).load('&lt;div id="test"&gt;&lt;/div&gt;', function(){});Syntax error, unrecognized expression: &gt;
  • this: en.wikipedia.org/wiki/Data_URI_scheme#JavaScript - 没关系,并非所有浏览器都支持该 URI,我只用 html() 替换了它。
【解决方案3】:

试试看:

$(this).load("<?php $this->load->view('slideshow','','true'); ?>", function() { ......  }

请注意,我使用单引号,第三个参数为 true。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 2020-11-16
    • 1970-01-01
    相关资源
    最近更新 更多