我正在尝试通过下拉菜单和文本框选择多个选项来过滤HTML页面上的结果。
一个例子是过滤用户半径10英里范围内的结果。 我有所有的机制工作,但我不确定我做得对。
所以我有类似的东西: http://slickdeals.net/deals/tech/
如果过滤器选项位于页面左侧,则人们可以按价格范围,评级等进行过滤。 所以我的第一个问题是: 使用javascript我将如何开始为URL参数添加过滤器选项?
现在我正在做这样的事情:
$('#FilterLocation').on('change', function () {
window.location.replace("?lat=" + place.geometry.location.lat() + "&lng=" + place.geometry.location.lng());
});
$('#FilterPrice').on('change', function () {
window.location.replace("?price=" + #FilterPrice.val());
});
然后列表继续,因为你可以看到我的过滤器列表有20个选项,然后我的javascript代码才开始增长,变得凌乱和丑陋真的很快。我知道必须有更好的方法来做到这一点,如何?
还有第二个问题。一旦我们通过URL进入我的控制器的部分,我正在使用PHP ..我通过在MySQL中执行WHERE查询返回结果。
所以看起来像:
if ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif (&& $State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} else {
$query = "select * from posts";
}
正如你所看到的,我只是做了一堆elseif来检查变量是否为空并根据它进行查询。一旦我的过滤器选项开始变大,这也会增长。
具体数据已被更改,并不重要,我真正想要找到的是: 1.使用javascript / jquery将url params添加到url的最佳方法是什么。 2.如果没有杂乱的代码,我如何在MySQL中过滤这些URL参数。
答案 0 :(得分:0)
问题的第一部分: 只需使用
之类的东西从表单中获取JSON中的所有内容即可json = {}
$('input[data-send="true"]').forEach(function() { //example selector
key = $(this).getattr("name");
value = $(this).val();
json[key] = value;
});
然后使用
之类的东西将其解析为URIvar uri = Object.keys(json).map(function(key){
return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
}).join('&');
您可以轻松地撤消重新加载值的过程。
至于PHP清理 - 您可以考虑编写某种处理程序,其中每个URI都会有不同的侦听器......但这样做会有些过分:使用{{switch
可能enum
1}?在过去的3年里,Haven编写了很多PHP代码。
答案 1 :(得分:0)
我个人认为你最好的选择是使用ajax (在本例中为jQuery)表单,然后是一个处理你的php的类。这是一个基本的例子(来自我使用的类的snippit,但为此目的进行了修改)。这不仅仅是复制和粘贴,而是为了让您了解可能需要的内容:
不确定您使用的是mysqli
还是PDO
,此课程使用PDO
:
<强> /classes/Database.php 强>
<?php
class Database
{
private $con,
$query,
$bind,
$sql;
private static $singleton;
public function __construct()
{
// Return self for lower-resourse reuse
if(empty(self::$singleton))
self::$singleton = $this->connection();
}
/*
** @description This will connect to your database, db creds requried
*/
public function connection($host = 'localhost',$database = 'database',$username = 'root',$password = '')
{
// Some settings for the PDO connection
$settings = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false);
// Saves the connection and returns it
$this->con = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password,$settings);
return $this->con;
}
/*
** @description creates the values string with bind array
*/
public function getSelectStr($array)
{
if(!is_array($array))
return;
$this->sql = array();
$i = 0;
foreach($array as $key => $value) {
$aKey = ":{$i}";
$this->bind[$aKey] = $value;
$this->sql[] = "`{$key}` = {$aKey}";
$i++;
}
return (!empty($this->sql))? ' WHERE '.implode(" and ",$this->sql) : '';
}
/*
** @description This queries the database
*/
public function query($sql,$bind = false)
{
$this->bind = false;
try {
if(empty($bind)) {
$this->query = self::$singleton->query($sql);
}
else {
foreach($bind as $key => $value) {
$key = trim($key,':');
$bkey = ":{$key}";
$this->bind[$bkey] = $value;
}
$this->query = self::$singleton->prepare($sql);
$this->query->execute($this->bind);
}
}
catch (PDOException $e){
die($e->getMessage());
}
return $this;
}
/*
** @description This fetches results if a select query sent
*/
public function getResults()
{
while($results = $this->query->fetch()) {
$row[] = $results;
}
return (!empty($row))? $row : 0;
}
/*
** @description This will retrieve the bind array
*/
public function getBind()
{
return $this->bind;
}
}
这是表单以及内容将丢弃的位置:
<强>的index.php 强>
<form method="post">
<select class="dynamic" name="option1">
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
<select class="dynamic" name="option2">
<option value="one one">One</option>
<option value="two two">Two</option>
<option value="three three">Three</option>
</select>
</form>
<!-- Here is where content will populate on ajax response -->
<div id="dropspot"></div>
jQuery处理onchange
和ajax
<强>的index.php 强>
<script>
$(document).ready(function() {
// On change of any class named "dynamic"
$(this).on('change','.dynamic', function () {
// Get the form
var thisForm = $(this).parents('form');
// Get data from form
var formData = thisForm.serialize();
console.log(formData);
$.ajax({
// Use this page url to process the ajax
url: '/processor.php',
// Send via $_POST
type: 'post',
// Send the form data
data: formData,
// On success write the response to the container
success: function(response) {
$('#dropspot').html(response);
}
});
});
});
</script>
这是为主要内容创建html的页面:
<强> /processor.php 强>
<?php
// This is the page labeled "processor.php" in the ajax script
if(!empty($_POST)) {
require(__DIR__.'/classes/Database.php');
// Create new database instance
$con = new Database();
// Generate a string and bind array from post
$qStr = $con->getSelectStr($_POST);
// Create the statement
echo
$statement = "SELECT * from `posts`{$qStr}";
// Get the bind array
$bind = $con->getBind();
print_r($bind);
// Get the results
$results = $con->query($statement,$bind)->getResults();
print_r($results);
exit;
}
?>
php页面的结果将是:
SELECT * from `posts` WHERE `option1` = :0 and `option2` = :1
Array
(
[:0] => three
[:1] => three three
)