AJAX - 代码签名中的PHP显示帖子并限制它们

时间:2016-09-09 12:02:55

标签: php jquery ajax codeigniter

所以我是ajax的新手而不是那么"亲"在PHP,我需要帮助。

我创建了一个ajax调用,在document.ready上显示来自DB的帖子

$.ajax({
        type:"POST",
        url:"testphp.php",
        datatype: 'json',
        success:function myFunction(response) {
            var arr = JSON.parse(response);
            var i;
            var out = " ";

            for(i = 0; i < arr.length; i++) {
                out += 
                    "<div id='"+arr[i].ID+"' class='grid-item "+arr[i].shape+"'>
                        <div class='grid_content'>"+arr[i].img_holder+"</div><div class='grid_title red'>"+arr[i].naslovhj+"</div>
                        <div class='content_grid'></div>
                    </div>"
            }
            out += " ";
            document.getElementById("grids").innerHTML = out;

            console.log("uspjelo"); 
        },
        error:function(){
            $("#ea").html('There was an error updating the settings');
        }   
}); 

testphp.php中的内容是:

$conn = new mysqli($servername, $username, $password, $dbname);
$myArray = array();
if ($result = $conn->query("SELECT * FROM postovi")) {
    $tempArray = array();
    while($row = $result->fetch_object()) {
        $tempArray = $row;
        array_push($myArray, $tempArray);
    }
    echo json_encode($myArray);
}

$result->close();

如何制作它以便每页显示10个帖子,并且新页面在这个页面的底部加上(当我滚动到页面底部时,它会附加10个帖子)

我尝试了几个无限卷轴,但他们没有按照我想象的那样工作。

编辑: 如果这可以通过中间的ajax完成并且我猜想需要一些php模型会很酷

编辑2:

查看代码:

来自DB的所有内容都将转换为此格式的#GRIDS元素

    <?php
      defined('BASEPATH') OR exit('No direct script access allowed');
      ?><!DOCTYPE html>
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <script src="https://code.jquery.com/jquery-2.2.2.js" integrity="sha256-4/zUCqiq0kqxhZIyp4G0Gk+AOtCJsY1TA00k5ClsZYE=" crossorigin="anonymous"></script>
      <script src="https://npmcdn.com/packery@2.0/dist/packery.pkgd.js"></script>
      <script src="src/jquery.keep-ratio.js"></script>
      <link href='https://fonts.googleapis.com/css?family=Roboto+Condensed' rel='stylesheet' type='text/css'>
      <title>KO web</title>
      </head>

      <body>

<div class="grid" id="grids">
  <div class="grid-item grid-normal">
      <div class="grid_content"><img src=""></div>
        <div class="grid_title red">
              title
            </div>
        <div class="content_grid">
        </div>

  </div>

</body>

<script>

$( document ).ready(function() {



//ajax tes
              $.ajax({
                  type:"POST",
                  url:"testphp.php",
        datatype: 'json',
        success:function myFunction(response) {
        var arr = JSON.parse(response);
        var i;
        var out = " ";

        for(i = 0; i < arr.length; i++) {
            out += 
     "<div id='"+arr[i].ID+"' class='grid-item "+arr[i].shape+"'><div class='grid_content'>"+arr[i].img_holder+"</div><div class='grid_title red'>"+arr[i].naslovhj+"</div><div class='content_grid'></div></div>"
        }
        out += " ";
        document.getElementById("grids").innerHTML = out;

                  console.log("uspjelo"); 
    }

            ,
            error:function(){
                $("#ea").html('There was an error updating the settings');
            }   
          }); 


//end off ajax test


setTimeout(function(){
$('.grid_title').each(function() {
    var mrs = $(this).innerHeight();
    $(this).css("margin-bottom", "-" + mrs + "px");
});}, 100);


$( document ).ajaxComplete(function() {


$('.grid').packery({
  // options
  itemSelector: '.grid-item',
  gutter: 0
});

 var clickDisabled = false;
 counter_p = 0;
$(".grid-item").click(function(){
  counter_p ++;
  if(counter_p == 1){
  $(this).attr("id", "active-grid-item-momentum");    
  $(this).children(".content_grid").attr("id", "active_cont");
  $(this).children(".grid_title").css("display","none");
  var width1 = document.getElementById('active-grid-item-momentum').offsetWidth;
  var height0 = document.getElementById('active-grid-item-momentum').offsetHeight;
  $(this).children(".grid_content").css("height", height0 + "px");
  $(this).children(".grid_content").css("width", width1 + "px");
  $(this).append( "<div id='close_all'>Test</div>" );
  $(this).css("cursor", "default")
  document.getElementById('active-grid-item-momentum').style.pointerEvents = 'none';
  document.getElementById('active_cont').style.pointerEvents = 'auto';
  $(this).children(".grid_content").children("img").css("opacity", "0");
  document.getElementById("active_cont").innerHTML="<h1>Sea world</h1><img src='../img/Aqua-Maris-Sea-World-game.png' style='float:left; margin-top:10px; margin-bottom:10px; margin-right:10px;' /><a href='http://www.google.com'>djlkjfkld</a>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse dapibus nisi sapien, ut scelerisque diam malesuada ut. Donec eget nibh vitae erat vehicula ullamcorper. In vitae ultricies erat. Nam at dignissim arcu. Nunc nec metus ac sem porttitor pulvinar sed vel ipsum. Phasellus nec velit sapien. Quisque vel pretium purus. In at massa nibh. Aliquam condimentum mauris nunc, ac consequat dolor scelerisque sed. Nullam sed mi vitae massa accumsan tincidunt. Curabitur in sem blandit eros interdum molestie. Sed ultricies sem ac ex consequat mollis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Integer sollicitudin nulla ac velit imperdiet gravida.Maecenas sed dictum leo. Mauris ac diam nec ex lobortis blandit in vitae sapien. Etiam a sodales augue, sollicitudin mattis ligula. In elementum ligula nunc, et porta purus tincidunt eu. Etiam bibendum interdum lectus. Sed convallis ornare placerat. Nullam sodales eget dui quis sodales. Donec consequat nisl eget sapien cursus semper. Pellentesque finibus facilisis nulla, sit amet pellentesque justo tristique et. Cras sodales nisl sed est euismod fringilla.Duis lacus ex, volutpat sed maximus et, dapibus in tortor. Vestibulum tristique lectus congue quam suscipit, quis varius leo consectetur. Proin enim eros, pretium sed purus eu, consectetur pulvinar velit. Pellentesque enim nunc, iaculis ut lacus ut, posuere dapibus eros. Integer ac sem molestie sem iaculis cursus. Vivamus quis eros in est molestie luctus eget quis massa. Curabitur ut metus sodales, eleifend dolor sit amet, dapibus magna. Phasellus a est libero. Nunc sed dui at felis varius semper. Ut neque metus, volutpat sed tortor a, venenatis consectetur ex.Ut ullamcorper placerat mattis. Aenean finibus mauris a dui volutpat, at vulputate justo porta. Proin scelerisque eleifend quam eget congue. Nunc laoreet cursus massa sit amet condimentum. Sed sit amet semper augue, et ultricies arcu. Nullam iaculis euismod est interdum tristique. Praesent magna velit, volutpat a varius eget, cursus vel ex. Morbi molestie leo quis accumsan fringilla. Donec in facilisis nisi, sit amet dictum ligula. Aenean vel sodales dolor, nec elementum mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vivamus at tristique dolor. Sed blandit venenatis turpis, sed varius nisi euismod a. Integer quis nisl lorem.Sed lorem velit, varius non lacus vitae, tincidunt porttitor nibh. Aliquam facilisis vulputate ex, eget fermentum sapien congue eu. Nunc ac scelerisque ipsum, vel iaculis felis. Pellentesque iaculis, ligula at ullamcorper ullamcorper, erat justo egestas magna, ut egestas quam metus vel enim. Mauris elementum ut ex eget venenatis. Quisque quis porttitor nibh. Quisque fermentum mauris in libero commodo, vel viverra nisl faucibus. Curabitur posuere metus luctus facilisis pellentesque. Integer rutrum augue ac odio tristique eleifend. Integer semper ante vitae dapibus varius. Quisque interdum turpis vel enim tempor sollicitudin quis maximus est. Mauris efficitur dui ac velit mattis ultrices. Curabitur elementum dictum felis, sed eleifend ex elementum sed.! massa accumsan tincidunt. Curabitur in sem blandit eros interdum molestie. Sed ultricies sem ac ex consequat mollis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Integer sollicitudin nulla ac velit imperdiet gravida.Maecenas sed dictum leo. Mauris ac diam nec ex lobortis blandit in vitae sapien. Etiam a sodales augue, sollicitudin mattis ligula. In elementum ligula nunc, et porta purus tincidunt eu. Etiam bibendum interdum lectus. Sed convallis ornare placerat. Nullam sodales eget dui quis sodales. Donec consequat nisl eget sapien cursus semper. Pellentesque finibus facilisis nulla, sit amet pellentesque justo tristique et. Cras sodales nisl sed est euismod fringilla.Duis lacus ex, volutpat sed maximus et, dapibus in tortor. Vestibulum tristique lectus congue quam suscipit, quis varius leo consectetur. Proin enim eros, pretium sed purus eu, consectetur pulvinar velit. Pellentesque enim nunc, iaculis ut lacus ut, posuere dapibus eros. Integer ac sem molestie sem iaculis cursus. Vivamus quis eros in est molestie luctus eget quis massa. Curabitur ut metus sodales, eleifend dolor sit amet, dapibus magna. Phasellus a est libero. Nunc sed dui at felis varius semper. Ut neque metus, volutpat sed tortor a, venenatis consectetur ex.Ut ullamcorper placerat mattis. Aenean finibus mauris a dui volutpat, at vulputate justo porta. Proin scelerisque eleifend quam eget congue. Nunc laoreet cursus massa sit amet condimentum. Sed sit amet semper augue, et ultricies arcu. Nullam iaculis euismod est interdum tristique. Praesent magna velit, volutpat a varius eget, cursus vel ex. Morbi molestie leo quis accumsan fringilla. Donec in facilisis nisi, sit amet dictum ligula. Aenean vel sodales dolor, nec elementum mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vivamus at tristique dolor. Sed blandit venenatis turpis, sed varius nisi euismod a. Integer quis nisl lorem.Sed lorem velit, varius non lacus vitae, tincidunt porttitor nibh. Aliquam facilisis vulputate ex, eget fermentum sapien congue eu. Nunc ac scelerisque ipsum, vel iaculis felis. Pellentesque iaculis, ligula at ullamcorper ullamcorper, erat justo egestas magna, ut egestas quam metus vel enim. Mauris elementum ut ex eget venenatis. Quisque quis porttitor nibh. Quisque fermentum mauris in libero commodo, vel viverra nisl faucibus. Curabitur posuere metus luctus facilisis pellentesque. Integer rutrum augue ac odio tristique eleifend. Integer semper ante vitae dapibus varius. Quisque interdum turpis vel enim tempor sollicitudin quis maximus est. Mauris efficitur dui ac velit mattis ultrices. Curabitur elementum dictum felis, sed eleifend ex elementum sed.!"; 
  $(this).css("width", "calc(100% - 10px)");  


</script>

2 个答案:

答案 0 :(得分:1)

有多种方法可以完成这项工作,但这是我如何使用Codeigniter设计它。这假设您已正确完成所有必需的配置设置,包括application/config/config.phpapplication/config/database.phpapplication/config/routes.phpapplication/config/autoload.php中的配置设置。

使用模型/视图/控制器模式,可以创建多个文件。首先是控制器。这将是默认控制器,并为Ko_web.php。在routes.php我们需要此设置:$route['default_controller'] = 'ko_web';完成后您可以输入http://example.com并直接转到ko_web函数将接管的index()控制器。< / p>

<强> /application/controllers/Ko_web.php

class Ko_web extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('postovi_model');
        $this->load->helper('url'); //could and maybe should be 'autoloaded'
    }

    public function index()
    {
        $data = array(); //empty but $data is set just in case

        //get the first 10 rows of users
        $rows = $this->postovi_model->get_next_10();
        if(isset($rows))
        {
            //We got rows, make the html from them
            //FYI, The array key 'users' becomes the variable $users in the view
            $data['users'] = $rows;
            //the view is returned as a string of html fully 
            //populated with rows of user's data
            $data['users'] = $this->load->view('user_rows_view', $data, TRUE);
        }

        //Using method chaining here to load multiple views cause it's cool and effcient
        $this->load
            //start the page with the reuseable header view file, passing page title too
            ->view('header_view', array('title' => "User Info")) 
            //Next, put the rows in the grid structure
            //note that if $data['users'] is not set the resulting view will have no user rows
            ->view('user_grid_view', $data)
            //add closing html tags, and in this case the javascript
            ->view('page_close_view', $data);
}

    public function load_more()
    {
        $offset = $this->input->post('offset');
        if($offset)
        {
            $new_rows = $this->postovi_model->get_next_10($offset);
            if(isset($new_rows))
            {
                $data['users'] = $new_rows;
                //this will return (echo) html to the ajax success function
                //CI takes care of making the correct response headers - sweet
                $this->load->view('user_rows_view', $data);
            }
            else
            {
                echo ""; //return an empty string
            }
        }
    }

}

index()函数将加载(最多)前10行用户信息。

模型很简单,只有一个返回行数组的函数。

<强> /application/models/Postovi_model.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Postovi_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function get_next_10($offset = 0)
    {
        $this->db->limit(10, $offset);
        $query = $this->db->get("postovi"); //same as "SELECT * FROM postovi LIMIT 10, $offset "
        //Got rows? If so return an array of row arrays, or return NULL if nothing retrieved
        return $query->num_rows() > 0 ? $query->result_array() : NULL;
    }

}

如果没有找到行,模型将返回NULL。 控制器检查这种情况并做出相应的响应。

视图主要分为多个文件,因此可以轻松地重用标记。无论如何,每页的顶部都需要相同的信息。

<强>应用/视图/ header_view.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="https://code.jquery.com/jquery-2.2.2.js" integrity="sha256-4/zUCqiq0kqxhZIyp4G0Gk+AOtCJsY1TA00k5ClsZYE=" crossorigin="anonymous"></script>
        <script src="https://npmcdn.com/packery@2.0/dist/packery.pkgd.js"></script>
        <script src="src/jquery.keep-ratio.js"></script>
        <link href='https://fonts.googleapis.com/css?family=Roboto+Condensed' rel='stylesheet' type='text/css'>
        <title><?= isset($title) ? $title : "KO web"; ?></title>
    </head>
    <body>

请注意能够传递页面的标题,但如果没有传递,我们会有回落。

下一个视图是网格结构。这里有两点需要注意。首先是var $users。控制器从另一个视图创建此数据,该视图将在此视图之后显示。 $users的值是网格行的html字符串。如果设置了$users,它将回显到此视图并最终回显到浏览器。

要注意的第二件事是我加了一个&#34;加载更多......&#34;网格底部的按钮。它与javascript绑定并将启动ajax调用。确保ajax工作后,您可以实现滚动加载器。

<强> /application/views/user_grid_view.php

<div class = "grid" id = "grids">
    <div class = "grid-item grid-normal">
        <div class = "grid_content"><img src = ""></div>
        <div class = "grid_title red">title</div>
        <div class = "content_grid" id='user-rows'>
            <?php
            if(isset($users))
            {
                echo $users;
            }
            ?>
        </div>
    </div>
    <button type="button" id="more_rows">Load More...</button>
</div>

接下来是构建用于显示的网格项行的视图页面

<强> /application/views/user_rows_view.php

<?php
if(isset($users))
{
    foreach($users as $user)
    {
        //It's easier to drop in and out of the PHP interpreter than to concantenate strings.
        //There is no execution penalty for doing it.
        //Also, it's easer to read and easier to write.
        ?>
        <div id='<?= $user['ID']; ?>' class='grid-item <?= $user['shape']; ?>'>
            <div class='grid_content'><?= $user['img_holder']; ?></div>
            <div class='grid_title red'> <?= $user['naslovhj']; ?></div>
            <!--Is the following needed?-->
            <!--<div class='content_grid'></div>-->
        </div>
        <?php
    }
}

希望我能掌握所有的正确名称,并了解你想要的布局。

好的,最后一个视图有javascript和相应的html标签来关闭网页。

<强> /application/views/page_close_view.php

<script>
    $(document).ready(function () {
    var baseURL = <?= base_url(); ?>;
    var row_count;

        $('#more_rows').on('click', function () {
            //what's the offset?
            row_count = $('.grid-item').length || 0;

            $.ajax({
                type: "POST",
                url: baseURL + "Ko_web/load_more",
                data: {offset: row_count},
                datatype: 'html',
                success: function (response) {
                    if (response === "") {
                        alert("No rows to show.");
                    } else {
                        $('#user-rows').append(response);
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log(jqXHR, textStatus, errorThrown);
                    //alert("your message here");
                    //$("#ea").html('There was an error updating the settings');
                }
            });
        });

    });
    /*
     * Note: I left out the remaineder of the javascript from your question 
     * because it did not seem to pertain to the answer you seek.
     */
</script></body></html>

该脚本计算屏幕上由类&#34; grid-item&#34;标识的行数。我无法真正测试这个,但我认为我做对了。此数字将传递给控制器​​,并将其用作数据库查询的偏移量。

因为控制器返回完全形成的html,所以将它插入需要去的DOM中是很容易的。我将id='user-rows'添加到了content_grid周围的div中,以便于找到正确的插入点。

毫无疑问,这会给你带来很多问题。以下是您已经拥有的CodeIgniter Documentation,但其他读者可能会感兴趣。

肯定存在拼写错误,也许还有一些语法错误。但逻辑应该非常接近,并且结构在CodeIgniter上是有效的。享受!

答案 1 :(得分:0)

通过邮寄

发送页码
    $.ajax({   
         type:"POST",
         url:"testphp.php",
         datatype: 'json',
         data : {page: 1/* show page*/}
         success:function myFunction(response) {
             var arr = JSON.parse(response);
             var i;
             var out = " ";
             for(i = 0; i < arr.length; i++) {
                 out += 
                   "<div id='"+arr[i].ID+"' class='grid-item "+arr[i].shape+"'>
                    <div class='grid_content'>"+arr[i].img_holder+"</div><div class='grid_title red'>"+arr[i].naslovhj+"</div>
                    <div class='content_grid'></div>
                </div>"
            }
            out += " ";
            document.getElementById("grids").innerHTML = out;

            console.log("uspjelo"); 
      },
      error:function(){
         $("#ea").html('There was an error updating the settings');
      }   
  }); 

计算偏移量,在结果中留一个间隔

// file testphp.php
$page = $_POST['page'];
$limit = 20;
$offset = ($page - 1) * $limit; //calculating next offset

$conn = new mysqli($servername, $username, $password, $dbname);
$myArray = array();
if ($result = $conn->query("SELECT * FROM postovi LIMIT ".$limit." OFFSET ".$offset)) {
    $tempArray = array();
    while($row = $result->fetch_object()) {
        $tempArray = $row;
        array_push($myArray, $tempArray);
    }
    echo json_encode($myArray);
}

$result->close();