我试图通过让用户通过下拉菜单和文本框选择多个选项来过滤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参数添加到url的最佳方法是什么。2.在没有混乱代码的情况下,如何在MySQL中过滤那些URL参数。
对于问题的第一部分:只需使用之类的东西将表单中的所有内容作为JSON获取即可
json = {}
$('input[data-send="true"]').forEach(function() { //example selector
key = $(this).getattr("name");
value = $(this).val();
json[key] = value;
});
然后使用类似的东西将其解析为URI
var uri = Object.keys(json).map(function(key){
return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
}).join('&');
您可以很容易地反向加载值。
至于PHP清理,您可以考虑编写某种处理程序,其中每一个URI都有不同的侦听器。。。但这太过分了:也许switch
使用enum
?在过去的3年里,我没有写过很多PHP代码。
我个人认为最好的选择是使用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
)