我有一个网页中的一些设备的过滤器,由复选框组成。无论何时单击其中一个复选框,我都会调用一个函数,将添加到对象中的复选框的值添加到对象中。我想通过ajax将这个对象发送到一个php文件,并用它来执行一些MySQL查询,然后从php返回结果并将它们显示在页面上。问题是,我错过了一些东西,因为我一直在我的js中得到一个parseerror。从jquery发送和处理关联数组到php
这里是我的代码: 设备filter.js
$(document).ready(function(){
$(".ez-checkbox").click(function() {
console.log("ok");
var re = {Brand: "", Cost: "", OS: ""};
$("#Brand :checkbox:checked").each(function(){
re.Brand += $(this).val()+" & ";
});
$("#Cost :checkbox:checked").each(function(){
re.Cost += $(this).val()+" & ";
});
$("#OS :checkbox:checked").each(function(){
re.OS += $(this).val()+" & ";
});
if(re.lenght==0){
}
else{
$.ajax({
method: "POST",
dataType: "json", //type of data
crossDomain: true,
data: re,
url:"./php/filtered-device-query.php",
success: function(response) {
//display the filtered devices
},
error: function(request,error)
{
console.log(request+":"+error);
}
});
}
});
});
filtere设备,query.php
<?php
//connection to db
$mysqli = new mysqli("localhost", "root", "", "my_db");
if (mysqli_connect_errno()) { //verify connection
echo "Error to connect to DBMS: ".mysqli_connect_error(); //notify error
exit(); //do nothing else
}
else {
//echo "Successful connection"; // connection ok
$devices =json_decode($_POST['re']);
echo var_dump($devices)."<br>";
$myArray = array();//create an array
$brand = rtrim($devices["Brand"], " &");
$cost = rtrim($devices["Cost"], " &");
$os = rtrim($devices["OS"], " &");
$query = " SELECT * FROM `devices` WHERE `Brand` = '$brand' AND 'Cost' = '$cost' AND 'OS' = '$os' ";
$result = $mysqli->query($query);
//if there are data available
if($result->num_rows >0)
{
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
//free result
$result->close();
//close connection
$mysqli->close();
}
?>
在此先感谢您的帮助!
我不是一个JS大师(远离它),但我可以告诉什么时候有什么东西被拼错了,这是'长期'。对于你的if(re.lenght == 0),这应该读作'length'。编辑:与@Saty关于你的专栏名称一起说。检查错误,会在这里帮助你。 –
来自列名称的引用换行在''Cost'='$ cost'和'OS'='$ os''处使用反向代码 – Saty
[Little Bobby](http://bobby-tables.com/)说[你的脚本存在SQL注入攻击的风险。](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)了解[prepared](http:// en .wikipedia.org/wiki/Prepared_statement)[MySQLi]的声明(http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)。即使[转义字符串](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string)是不安全的! –