如何使用 Ajax Json PHP 和 MySQL 应用排序和过滤


How to apply sorting and filtering using Ajax Json PHP & MySQL

嗨,我是初学者,我正在软件网站上工作。 我已经为网站构建了所有页面和布局,这是单独使用 HTML CSS 和 JAVASCRIPT 完成的简单部分,唯一剩下的就是为不同的软件制作主要类别页面,这对我来说很难。

我想在这样的类别页面上添加排序选项(见这里(用户应能够根据日期、名称、添加日期等对软件进行排序。并且还可以控制要显示的最大软件数量,例如20,30,100等

在我的 HTML 页面上,我有这些 div,我想在其中显示数据(不同的软件(来自MySQL数据库"security_software"(它是一个测试数据库(来自"internet_security"(它是一个测试表(

HTML Div's

  <div class="category-container">
    <div class="category-image"></div>
    <div class="category-desc"><a href="#">#</a><p>text</p></div>
    <div class="rating5" >Editors' rating: </div>
    <div class="category-download-btn"><a href="#">Download</a></div>
    <div class="category-buy-btn"><a href="#">Buy</a></div>
  </div>

经过一些研究,我得到了一个使用JSON AJAX PHP 和MySQL的解决方案

我有的 JAVASCRIPT 代码

<head>    
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$.ajax({
    url: 'ajax.php',
    dataType: 'json',
    success: function(response){
        data = '';
        $.each(response,function(i,val){
          data = '<div class="category-image">'+val.image+'</div>'+
        '<div class="category-link"><a href="#">'+val.id+'</a></div>'+
        '<div class="category-desc"><p>'+val.description+'</p> </div>'+
        '<div class="rating5" >'+val.rating+'</div>'+ 
        '<div class="category-download-btn"><a href="'+val.download+'">Download</a></div>'+ 
        '<div class="category-buy-btn"><a href="'+val.buy+'">Buy</a></div>';
        $('<div>').attr('id',i).html(data).appendTo('#response');
    });
    }
 });
</script>
</head>
 <body>
<div id='response'></div>   
 </body>

我有的PHP代码

<?php
$q=$_GET["q"]; 
$con = mysql_connect('localhost', 'root', '');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("security_software", $con);
$sql="SELECT * FROM internet_security ORDER by `".$q."` DESC" ;

$result = mysql_query($sql);
$response = array();
$i=0;
while($row = mysql_fetch_array($result))
  {
  $response[$i]['id']           =$row['id'];
  $response[$i]['title']        = $row['title'];
  $response[$i]['image']        = $row['image'];
  $response[$i]['description']  = $row['description'];
  $response[$i]['rating']       = $row['rating'];
  $response[$i]['download']     = $row['download'];  
  $response[$i]['buy']          = $row['buy'];
  $i++;
  }
mysql_close($con); 
echo json_encode($response);
?>

现在它根本不起作用,因为我在我拥有的 javascript 中没有任何地方可以附加这些代码(类别下拉列表(。

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="id">id</option>
<option value="title">title</option>
<option value="image">image</option>
<option value="description">description</option>
<option value="description">rating</option>
<option value="download">download</option>
<option value="buy">buy</option>
</select>
</form>

请帮助我在哪里可以附加这些代码以及如何使其工作,我完全困惑。

首先值得注意的是,如果您要显示表格数据...使用表格!它会让你的事情变得容易得多。

其次。构建你的代码和表,就好像Ajax不存在一样。最初在显示数据的页面上使用 PHP 填充数据。然后,连接列标题,以便它们链接到您的页面,但传递您要排序的列以及哪个方向。

<?
    $column = (isset($_GET["column"]) ? $_GET["column"] : 'id'); 
    $direction = (isset($_GET['direction']) ? $_GET['direction'] : 'asc');
    $con = mysql_connect('localhost', 'root', '');
    if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("security_software", $con);
    $sql="SELECT * FROM internet_security ORDER by '".$column."' " . $direction;

    $result = mysql_query($sql);
    $response = array();
    $i=0;
    while($row = mysql_fetch_array($result))
    {
        $response[$i]['id']           =$row['id'];
        $response[$i]['title']        = $row['title'];
        $response[$i]['image']        = $row['image'];
        $response[$i]['description']  = $row['description'];
        $response[$i]['rating']       = $row['rating'];
        $response[$i]['download']     = $row['download'];  
        $response[$i]['buy']          = $row['buy'];
        $i++;
    }
    mysql_close($con); 
?>
<div id="content">
    <table>
        <thead>
            <tr>
                <td><a href="table.php?column=id<?= (isset($_GET['column']) && $_GET['column'] == 'id' && !isset($_GET['direction']) ? '&direction=desc' : ''); ?>">ID</a></td>
                <td><a href="table.php?column=title<?= (isset($_GET['column']) && $_GET['column'] == 'title' && !isset($_GET['direction']) ? '&direction=desc' : ''); ?>">Title</a></td>
                <td><a href="table.php?column=rating<?= (isset($_GET['column']) && $_GET['column'] == 'rating' && !isset($_GET['direction']) ? '&direction=desc' : ''); ?>">Rating</a></td>
                <td><a href="table.php?column=download<?= (isset($_GET['column']) && $_GET['column'] == 'download' && !isset($_GET['direction']) ? '&direction=desc' : ''); ?>">Download</a></td>
            </tr>
        </thead>
        <tbody>
            <? foreach($response as $i => $row) : ?>
            <tr>
                <td><?= $row['id']; ?></td>
                <td><?= $row['title']; ?></td>
                <td><?= $row['rating']; ?></td>
                <td><?= $row['download']; ?></td>
            </tr>
            <? endforeach; ?>
        </tbody>
    </table>
</div>

上面的代码将进入单个PHP文件,没有任何其他HTML等。然后,在要显示此表的页面上,只需<? include('path-to-file.php'); ?>包含它即可。

最后。。。在显示表格的页面顶部,您将输入:

<?
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
    {
        include('path-to-file.php');
        die();
    }
?>

然后,上面的代码将检测 Ajax 请求,并仅提供包含新顺序数据的表。

然后,您需要使用 Javascript 通过以下方式将表替换为新的 HTML

$('#content table thead a').live('click', function(e)
{
    e.preventDefault();
    $.ajax(
    {
        url : $(this).attr('href'),
        success : function(resp)
        {
            $('#content').html($(resp).html());
        },
        error : function()
        {
            alert('There was a problem sorting your table...');
        }
    });
});

其中resp是包含 Ajax 响应的变量。

注意:这只是一种非常简单和粗糙(哦,未经测试(的处理情况的方法。您需要自己改进它,以防止任何与安全相关的问题,例如SQL注入。