duang8642 2015-12-07 17:12 采纳率: 0%
浏览 58

如何通过通过AJAX传递的URL从mysql请求数据

I am creating a page display a list of products and want to be able to filter by category, have pages, a item per page limit and a sort order

on the store page I do a database call to generate all categories and put them in a sidebar.

Then on click/change serialize all the date on the form using $('#form').serialize() then pass it to request_handler.php which will return the correct data.

The problem is, is that because it is all POST data there is no URL reference so people will not be able to link to the results from their choice similar to - http://www.asos.com/Men/Shirts/Cat/pgecategory.aspx?cid=3602#state=Rf989%3D6200%2C4885&parentID=Rf989&pge=0&pgeSize=36&sort=-1 Also you will not be able to go back and forth because it is all AJAX. I may be able to solve this with history JS but im not sure how to use a url to get the desired results.

<?php

    // Database config file, db login settings
    require_once '../inc/dbconfig.php';

    try {
    // connect to database;
    $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt_all_results = $conn->prepare('SELECT * FROM films ORDER BY category ASC');
    $stmt_all_results->execute();

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>

    <form id="store">
      <ul>
        <?php
          $category = null;
          while($r = $stmt_all_results->fetch()){
            if ($category != $r['category']) {
              $category = $r['category'];
                echo '<li>
                  <label for="cat-' . $category . '">
                    <input type="checkbox" name="cat[]" id="cat-'. $category .'" value="' . $category . '">'
                    . $category .
                  '</label>
                </li>';
            }
          }
        ?>
      </ul>
    </form>

<div class="result"></div>

<?php
  // close try
  } catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
  }
?>

<!-- LOAD JQUERY -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>

  function get_data(dat){
      $.post( "request_handler.php", dat)
      .done(function( data ) {
      $( ".result" ).html( data );
    });
  }

  $('li').change(function(){
      var dat = $('#store').serialize();
      get_data(dat);
  })

</script>

Request Handler Script

<?php

// Database config file
require_once '../inc/dbconfig.php';

$category =$_POST['cat'];

foreach ($category as $i){
    $options[] = "category='" . $i ."'";
}

$sql = "SELECT * FROM databse";

if (count($options)){
   $sql .= " WHERE " . implode(' OR ', $options);
}

try {
    // connect to database;
    $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt_all_results = $conn->prepare($sql);
    $stmt_all_results->execute();

    # default
    $get_pages = isset($_GET['page']) ? $_GET['page'] : 1;

    while($row = $stmt_all_results->fetch()) {
     $product_title = $row['title'];
     $product_image = $row['image_src'];
     $product_category = $row['category'];
     $product_id = $row['id'];
?>


<ul>
    <li>
        <img src="<?php echo $product_image; ?>">
        <h4><?php echo $product_title; ?></h4>
        <p><?php echo $product_category; ?></h4>
        <a href="product?id=<?php echo $product_id; ?>">More Info</a>
    </li>

</ul>

<?php
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}

?>

-if this post is confusing don't attack it just suggest rewording as i have been searching all day to solve this issue - thanks

  • 写回答

1条回答 默认 最新

  • duanlei5339 2015-12-07 18:42
    关注

    Mixing php with html/js/css nowadays is suggested bad practice. Some sort of framework and templating (separation of logic and data representation) is must have.

    Interactive clientside applications for data manipulation should be built using proper instruments, like angular.js, ember.js, whatever. If you try to do that in raw JavaScript, or even using jQuery, you will surely suffer a lot in both development and support of that application.

    If you don't want to confuse yourself with clientside frameworks and prefer oldschool way, I'd recommend you take a look at jQuery plugin called jqGrid. It has sorting, filtering, pagination, etc. built in, but you will have to do much work on the serverside anyway.

    Also if you want sorting/filtering/page number parameters to be passed in the URL, you'll have to initialize grid properly, set those parameters using grid API, and reload it.

    And I'd strongly recommend you try some sort of templating engine anyway. That will make your code much more clear and consistent.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。