我有一個網頁中的一些設備的過濾器,由複選框組成。無論何時單擊其中一個複選框,我都會調用一個函數,將添加到對象中的複選框的值添加到對象中。我想通過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)是不安全的! –