Javascript 如何使用CodeIgniter在Ajax中分割数组进行分页?
在我的模块的视图页面中有一个foreach循环,它从控制器检索图像网格(数量由“items_top”决定)。问题是所有项目都是同时加载的,因为此时没有设置分页 这是我的视图的代码:Javascript 如何使用CodeIgniter在Ajax中分割数组进行分页?,javascript,php,ajax,function,codeigniter,Javascript,Php,Ajax,Function,Codeigniter,在我的模块的视图页面中有一个foreach循环,它从控制器检索图像网格(数量由“items_top”决定)。问题是所有项目都是同时加载的,因为此时没有设置分页 这是我的视图的代码: <div class="row row-sm padder-lg "> <?php foreach ($top->tracks->track as $key => $value) { if($key >
<div class="row row-sm padder-lg ">
<?php
foreach ($top->tracks->track as $key => $value)
{
if($key >= $this->config->item("items_top"))
return false;
$image = $value->image[3]->text;
if($image == '')
$image = $value->image[2]->text;
if($image == '')
$image = base_url()."assets/images/no-cover.png";
?>
<div class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
<div class="item">
<div class="pos-rlt">
<a href="#">
<div class="item-overlay opacity r r-2x bg-black">
<div class="center text-center m-t-n">
<i class="icon-control-play i-2x"></i>
</div>
</div>
<a href="#">
<div class="r r-2x img-full" style="background:url('<?php echo $image; ?>') no-repeat top center; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover;">
<div style="height:180px;overflow:hidden;"></div>
</div>
</a>
</div>
<div class="padder-v">
<a href="#" class="text-ellipsis"><?php echo $value->name; ?></a>
<a href="#" class="text-ellipsis text-xs text-muted"><?php echo $value->artist->name; ?></a>
</div>
</div>
</div>
<?php
}
?>
<script>
$(".nav-sidebar li").removeClass("active");
$("#topTrack").addClass('active');
</script>
</div>
function _curl($url) {
$CI =& get_instance();
$ch = curl_init();
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,15);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
if(strtolower(parse_url($url, PHP_URL_SCHEME)) == 'https')
{
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,1);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1);
}
if($CI->config->item("proxy") != '')
{
curl_setopt($ch, CURLOPT_PROXY, $CI->config->item("proxy"));
}
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function getTopTracks($artist = false)
{
$CI =& get_instance();
$artist = econde($artist);
$url = "http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=".$CI->config->item("lastfm")."&format=json&limit=60&page=3";
$file_cache = 'cache/tracks_'.sha1("toptracks").".cache";
if($cache)
{
$json = $cache;
if (time()-filemtime($file_cache) > 24 * 3600) {
// file older than 24 hours
@unlink($file_cache);
}
}
else
{
$json = _curl($url);
if($CI->config->item("use_cache") == "1")
write_file($file_cache, $json);
}
if(!$artist)
$json = str_ireplace("toptracks","tracks",$json);
else
$json = remove_banned($json,true) ;
$json = str_ireplace("#text","text",$json);
$json = str_ireplace(":totalResults","",$json);
return remove_banned($json) ;
}
public function getTopTracks($return = false,$page = false)
{
$data['page'] = $page;
$data['top'] = json_decode(getTopTracks());
if(count($data['top']->tracks->track) <=1)
{
$this->config->set_item("auto_country", '0');
$data['top'] = json_decode(getTopTracks());
}
return $this->load->view(getTemplate('topTracks'),$data,$return);
}
这是我的控制器:
<div class="row row-sm padder-lg ">
<?php
foreach ($top->tracks->track as $key => $value)
{
if($key >= $this->config->item("items_top"))
return false;
$image = $value->image[3]->text;
if($image == '')
$image = $value->image[2]->text;
if($image == '')
$image = base_url()."assets/images/no-cover.png";
?>
<div class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
<div class="item">
<div class="pos-rlt">
<a href="#">
<div class="item-overlay opacity r r-2x bg-black">
<div class="center text-center m-t-n">
<i class="icon-control-play i-2x"></i>
</div>
</div>
<a href="#">
<div class="r r-2x img-full" style="background:url('<?php echo $image; ?>') no-repeat top center; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover;">
<div style="height:180px;overflow:hidden;"></div>
</div>
</a>
</div>
<div class="padder-v">
<a href="#" class="text-ellipsis"><?php echo $value->name; ?></a>
<a href="#" class="text-ellipsis text-xs text-muted"><?php echo $value->artist->name; ?></a>
</div>
</div>
</div>
<?php
}
?>
<script>
$(".nav-sidebar li").removeClass("active");
$("#topTrack").addClass('active');
</script>
</div>
function _curl($url) {
$CI =& get_instance();
$ch = curl_init();
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,15);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
if(strtolower(parse_url($url, PHP_URL_SCHEME)) == 'https')
{
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,1);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1);
}
if($CI->config->item("proxy") != '')
{
curl_setopt($ch, CURLOPT_PROXY, $CI->config->item("proxy"));
}
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function getTopTracks($artist = false)
{
$CI =& get_instance();
$artist = econde($artist);
$url = "http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=".$CI->config->item("lastfm")."&format=json&limit=60&page=3";
$file_cache = 'cache/tracks_'.sha1("toptracks").".cache";
if($cache)
{
$json = $cache;
if (time()-filemtime($file_cache) > 24 * 3600) {
// file older than 24 hours
@unlink($file_cache);
}
}
else
{
$json = _curl($url);
if($CI->config->item("use_cache") == "1")
write_file($file_cache, $json);
}
if(!$artist)
$json = str_ireplace("toptracks","tracks",$json);
else
$json = remove_banned($json,true) ;
$json = str_ireplace("#text","text",$json);
$json = str_ireplace(":totalResults","",$json);
return remove_banned($json) ;
}
public function getTopTracks($return = false,$page = false)
{
$data['page'] = $page;
$data['top'] = json_decode(getTopTracks());
if(count($data['top']->tracks->track) <=1)
{
$this->config->set_item("auto_country", '0');
$data['top'] = json_decode(getTopTracks());
}
return $this->load->view(getTemplate('topTracks'),$data,$return);
}
公共函数getTopTracks($return=false,$page=false)
{
$data['page']=$page;
$data['top']=json_解码(getTopTracks());
如果(计数($data['top']->tracks->track)配置->设置项目(“auto_country”,“0”);
$data['top']=json_解码(getTopTracks());
}
返回$this->load->view(getTemplate('topTracks'),$data,$return);
}
我需要对循环进行切片以对这些项目进行分页,我希望能够在底部添加一个按钮“加载更多”,但问题是Ajax,我不能使用$page=(int)getFromExternalInput();
,因为循环调用的是公共函数而不是url。
正确的分割方法是什么
我用询问的代码编辑了问题中的函数助手
希望这能对你的回答有所帮助。谢谢
好的,根据您的附加信息更新我的答案,我根据新信息创建了一个工作示例。但是,我必须为自己创建一个沙盒,它不会100%反映您的代码。我觉得您应该能够从这个答案中获得一些东西,并且您应该能够在自己的代码中实现它
代码确实需要一些优化
我正在/application/cache/lastfm中保存缓存文件
在这里,缓存可能是分页的一个问题,但我尽了最大努力想出了一个可行的示例
application/config/lastfm.php
application/libraries/curl.php
application/controllers/tracks.php
application/models/lastfm_model.php
class LastFM\u模型扩展了CI\u模型
{
/**
*
*@var类型
*/
受保护的美元期权;
/**
*
*@var类型
*/
受保护的$cache;
/**
*
*@var类型
*/
保护美元法;
/**
*
*@var类型
*/
受保护的$byPassCache=false;
公共函数构造()
{
父项::_构造();
$this->options=$this->config->config['lastfm'];
}
/**
*
*@param type$page
*/
公共函数getTracks($page=0,$bypass\u cache=false,$method='chart.gettoptracks')
{
$this->method=$method;
$this->cache=$this->_getCachePath();
$this->byPassCache=$bypass\u cache;
$url=$this->\u buildUrl($page);
if($bypass\u缓存){
返回数组(
'src'=>'curl',
“数据”=>$this->\u解析内容($this->\u获取($url),false)
);
}
如果($cache=$this->\u getCache()){
返回数组(
“src'=>“缓存”,
“数据”=>$this->\u解析内容($cache)
);
}
返回数组(
'src'=>'curl',
“数据”=>$this->\u解析内容($this->\u获取($url),false)
);
}
/**
*
*@param type$page
*@返回类型
*/
受保护的函数\u buildUrl($page=0)
{
$query\u data=array(
'method'=>$this->method,
'格式'=>'json',
“页面”=>$page,
'limit'=>$this->options['limit'],
'api_-key'=>$this->options['api_-key']
);
$query=http\u build\u query($query\u data);
返回$this->options['url'].?'.$query;
}
/**
*
*@param type$url
*@返回类型
*/
受保护的函数_fetch($url)
{
$this->load->library('curl');
$data=$this->curl->fetch($url);
$data=str#ireplace(数组('text','attr'),数组('text','attr'),$data);
如果(!$this->绕过缓存){
$this->\u setCache($data);
}
返回($data)?$data:假;
}
/**
*
*@返回类型
*/
受保护函数_getCachePath()
{
返回APPPATH。“cache/lastfm/{$this->method}.cache”;
}
/**
*
*@param type$data
*@返回类型
*/
受保护函数_setCache($data)
{
如果(文件_存在($this->cache)){
取消链接($this->cache);
}
如果(!空($data)){
返回文件内容($this->cache,$data);
}
}
/**
*
*@返回类型
*/
受保护的函数_getCache()
{
return(file\u exists($this->cache)&&(time()-filemtime($this->cache))<$this->options['cache\u time']
?$this->cache
:假;
}
/**
*
*@param type$content
*@param type$cache
*@返回类型
*/
受保护函数_parseContent($content,$cache=true)
{
如果($cache)
$content=file\u get\u contents($content);
返回json_解码($content);
}
}
application/views/lastfm/tracks.php
var SITE_URL=“”;
/**拉斯特姆**/
(函数($){
var lastFm={
/**
*
*@type类型
*/
选项:{
cache:false,
url:未定义,
键入:“获取”,
数据类型:“html”,
数据:{}
},
/**
*
*@returns{undefined}
*/
init:function(){
this.More=$(“a#More”);
this.trackList=$(“#track_list”);
this.trackList.on('click',this.More,$.proxy(this.handleEventClick,this));
},
/**
*
*@param{type}事件
*@returns{undefined}
class LastFM_Model extends CI_Model
{
/**
*
* @var type
*/
protected $options;
/**
*
* @var type
*/
protected $cache;
/**
*
* @var type
*/
protected $method;
/**
*
* @var type
*/
protected $byPassCache = false;
public function __construct()
{
parent::__construct();
$this->options = $this->config->config['lastfm'];
}
/**
*
* @param type $page
*/
public function getTracks($page=0, $bypass_cache=false, $method='chart.gettoptracks')
{
$this->method = $method;
$this->cache = $this->_getCachePath();
$this->byPassCache = $bypass_cache;
$url= $this->_buildUrl($page);
if($bypass_cache){
return array(
'src' => 'curl',
'data' => $this->_parseContent($this->_fetch($url), false)
);
}
if($cache = $this->_getCache()){
return array(
'src' => 'cache',
'data' => $this->_parseContent($cache)
);
}
return array(
'src' => 'curl',
'data' => $this->_parseContent($this->_fetch($url), false)
);
}
/**
*
* @param type $page
* @return type
*/
protected function _buildUrl($page=0)
{
$query_data = array(
'method' => $this->method,
'format' => 'json',
'page' => $page,
'limit' => $this->options['limit'],
'api_key' => $this->options['API_KEY']
);
$query = http_build_query($query_data);
return $this->options['url'] . '?' . $query;
}
/**
*
* @param type $url
* @return type
*/
protected function _fetch($url)
{
$this->load->library('curl');
$data = $this->curl->fetch($url);
$data = str_ireplace(array('#text', '@attr'), array('text', 'attr'), $data);
if(!$this->byPassCache){
$this->_setCache($data);
}
return ($data) ? $data : false;
}
/**
*
* @return type
*/
protected function _getCachePath()
{
return APPPATH . "cache/lastfm/{$this->method}.cache";
}
/**
*
* @param type $data
* @return type
*/
protected function _setCache($data)
{
if(file_exists($this->cache)){
unlink($this->cache);
}
if(!empty($data)){
return file_put_contents($this->cache, $data);
}
}
/**
*
* @return type
*/
protected function _getCache()
{
return ( file_exists($this->cache) && ( time() - filemtime($this->cache) ) < $this->options['cache_time'] )
? $this->cache
: false;
}
/**
*
* @param type $content
* @param type $cache
* @return type
*/
protected function _parseContent($content, $cache=true)
{
if($cache)
$content = file_get_contents($content);
return json_decode($content);
}
}
<div id="track_list">
<?php echo $tracks_view; ?>
</div>
<script>
var SITE_URL = "<?php echo site_url();?>";
</script>
<script>
/** LastFm **/
(function($){
var lastFm = {
/**
*
* @type type
*/
options : {
cache : false,
url : undefined,
type : "GET",
dataType : "html",
data : {}
},
/**
*
* @returns {undefined}
*/
init : function(){
this.More = $("a#more");
this.trackList = $("#track_list");
this.trackList.on('click', this.More, $.proxy(this.handleEventClick, this));
},
/**
*
* @param {type} event
* @returns {undefined}
*/
handleEventClick : function(event){
event.preventDefault();
var target, pageId;
target = event.target;
pageId = parseInt($(target).attr('data-pageId'));
$(target).remove();
this.pageID = pageId+1;
this.fetch(this.pageID);
},
/**
*
* @returns {undefined}
*/
fetch : function(pageId){
this.options.url = SITE_URL + "/tracks/get/"+pageId;
this.dojax().then(
$.proxy(this.handleResponse, this),
$.proxy(this.handleErrors, this)
);
},
/**
*
* @returns {unresolved}
*/
dojax : function(){
return $.ajax(this.options).promise();
},
/**
*
* @param {type} response
* @returns {undefined}
*/
handleResponse : function(response){
this.More.remove();
this.trackList.append(response);
$("html, body").animate({
scrollTop : $("[data-pageSlideId="+this.pageID+"]").filter(':last').offset().top
});
},
/**
*
* @param {type} error
* @returns {undefined}
*/
handleErrors : function(error){
}
};
lastFm.init();
}(jQuery));
</script>
<div id="page_<?php echo $statistics->page;?>">
<?php
$columnsPerRow = 4;
foreach(array_chunk($tracks['data']->tracks->track, $columnsPerRow) as $track): ?>
<div class="row" data-pageSlideId="<?php echo $statistics->page;?>">
<?php foreach($track as $trac):?>
<?php $image = (!empty($trac->image[2]->text)) ? $trac->image[2]->text : false;?>
<div class="large-3 medium-6 columns text-center" >
<div class="panel" style="background: url('<?php echo $image;?>') no-repeat;background-size: cover;">
<h6><?php echo $trac->name;?></h6>
<h5><?php echo $trac->artist->name;?></h5>
</div>
</div>
<?php endforeach;?>
</div>
<?php endforeach; ?>
</div>
<div class="row">
<div class="large-12 columns text-center">
<a href="" class="button" id="more" data-pageId="<?php echo $statistics->page;?>">Load More...</a>
</div>
</div>
<?php
#model fuction that take the list data from db
public function listSomething($listStart, $numberOfRows)
{
$this->db->select('login, nome');
$this->db->from('list');
$this->db->limit($numberOfRows, $listStart);
$queryUsuario = $this->db->get();
return $queryUsuario->result();
}
#controller fuction
public function listSomething ()
{
#pego as váriaveis do datatables via post.
$numeroDeRegistros = intval($this->input->post('length'));
$listStart = $this->input->post('start');
#Carega o model de usuario.
$this->load->model('UsuarioModel');
#Cria uma váriavel para armazenar o resultado já no formato do DataTables.
#Pega uma lista de usuário com parâmetros de paginação.
$list = listSomething($listStart, $numberOfRows);
#Conta os usuário registrados no banco.
$listCount = count($list);
#Pega o tamanho que a lista deve ter, passado pelo Datatables.
$listLength = intval($this->input->post('length'));
#Se o tamanho da lista for maior que a propria lista, o total é o tamanho.
if ( $listLength > $listCount ) {
$listLength = $listCount;
}
#Se o fim da lista é maior que o total da lista, então o fim da lista é o total.
$listEnd = $listStart + $listLength;
if ( $listEnd > $listCount ) {
$listEnd = $listCount;
}
#Formata os dados antes de passar para json.
for($i = 0; $i < $listEnd-$listStart; $i++) {
foreach($list[$i] as $var => $value) {
$list["data"][$i][] = $value;
}
$list["data"][$i][] =
'
<a href="javascript:;" class="btn btn-xs default blue" id="editaUsuarioBnt"><i class="fa fa-pencil"></i> Editar</a>
<a href="javascript:;" class="btn default btn-xs red" id="excluiUsuario"><i class="fa fa-trash-o"></i> Excluir </a>
<a href="javascript:;" class="btn btn-xs default yellow"><i class="fa fa-times"></i> Redefinir Senha</a>
';
}
#Envia a lista para formatar em json.
$this->jsonDataTables($list, $listCount);
}
#library function that append some datatables data and output json.
public function jsonDataTables (&$list, $totalDaLista)
{
#Gravo na variável o valor de quantas
$sEcho = intval($this->input->post('draw'));
if ( $list != null ) {
if (isset($_REQUEST["customActionType"]) && $_REQUEST["customActionType"] == "group_action") {
$list["customActionStatus"] = "OK"; // pass custom message(useful for getting status of group actions)
$list["customActionMessage"] = "Group action successfully has been completed. Well done!"; // pass custom message(useful for getting status of group actions)
}
$list["draw"] = $sEcho;
$list["recordsTotal"] = $totalDaLista;
$list["recordsFiltered"] = $totalDaLista;
echo json_encode($list);
}
else {
echo json_encode("");
}
}
#model fuction that take the list data from db
public function listSomething($listStart, $numberOfRows)
{
$list = getMyExternalImages();
return array_slice($list, $listStart, $numberOfRows);
}
#I'll probably need this to count how many results you have
public function countExternalImages()
{
$list = getMyExternalImages();
return count($list);
}