通过AJAX加载文件与CodeIgniter / MVC [英] Loading files via AJAX with CodeIgniter/MVC
问题描述
我目前正在重写整个网站的我,使其与CI兼容。我是相当新的CI和一般的MVC模式。我遵循此教程,并且为MVC模式的视图部分做了一个相当不错的模板。事情是,很多我的网站使用jQuery / AJAX,使其更加动态。例如,在我的网站的所有页面上,我有一个输入字段,使用jQuery在加密时加载PHP文件。
I'm currently in the process of rewriting an entire site of mine so that it's compatible with CI. I'm fairly new with CI and the MVC pattern in general. I followed this tutorial and have made a pretty decent template for the view part of the MVC pattern. The thing is, a lot of my site uses jQuery/AJAX to make it more dynamic. For example, on all of my pages on my site, I have an input field that uses jQuery to load a PHP file upon keyup.
<script type="text/javascript">
$("#search_bar").keyup(function(){
var search = $("#search_bar").val();
var url = "search_bar.php";
var data = "q="+ search;
$('#livesearch').load(url, data);
$("#livesearch").slideDown("fast");
});
</script>
<input type='text' maxlength='30' id='search_bar' autocomplete='off' placeholder='Browse Teams' />
<div id='livesearch' style='display:none;'></div>
加载结果所需的所有后端工作都发生在通过jQuery加载的PHP文件中search_bar.php)。所以,search_bar应该是自己的视图,它是由自己的控制器触发,然后由一个名为search_bar的模型建模?再次,我是新的MVC模式,不太确定如何正确地整合AJAX与面向对象的框架,如CI。
All of the backend work that's required to load the results happens in the PHP file that loaded via jQuery (search_bar.php). So, should "search_bar" be its own View that's triggered by its own Controller and then Modeled by a model called "search_bar"? Again, I'm very new to the MVC pattern and am not quite sure how properly integrate AJAX with a object oriented framework like CI.
感谢
推荐答案
在 ajax
请求中直接调用视图不是一个好的习惯,查看或直接在控制器的函数中执行操作
Directly calling the view in ajax
request is not a good practice call the controller which loads the view or directly do the stuff in the controller's function
<script type='text/javascript'>
$('#search_bar').keyup(function(){
$.ajax({
url: 'yourcontrollername/search_bar_yourfunction',
type:'POST',
data: {q: search,
success: function(result){
$("#livesearch").html(result);
$("#livesearch").slideDown("fast");
}
});
});
</script>
您的控制器代码
class yourcontrollername extends My_Controller {
public function search_bar_yourfunction() {
//do your stuff and store in the $data[] array
$this->load->view("search_bar",$data); //search_bar.php
die();
}
}
}
这篇关于通过AJAX加载文件与CodeIgniter / MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!