0
不可能走出變量的這段話我嘗試了很多東西......但是,由於它是一個通常不復雜的事情......傳遞一個JS變量到PHP阿賈克斯
我想傳遞一個變量:SerialNumberJS這是在JS(我通過URL檢索:getUrlParameter函數)到PHP文件!這個變量將被用於PHP中進行基本查詢。然後回到JS來顯示圖形!
請幫助:)
$(document).ready(function(){
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
var SerialNumberJS = getUrlParameter('SerialNumber');
console.log(SerialNumberJS);
$.ajax({
url : "graphdata.php",
type : "GET",
success : function(data){
console.log(data);
var heure = [];
var payload = [];
for(var i in data) {
heure.push("Heure " + data[i].heure);
payload.push(data[i].payload);
}
var chartdata = {
labels: heure,
datasets: [
{
label: "payload",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(59, 89, 152, 0.75)",
borderColor: "rgba(59, 89, 152, 1)",
pointHoverBackgroundColor: "rgba(59, 89, 152, 1)",
pointHoverBorderColor: "rgba(59, 89, 152, 1)",
data: payload
}
]
};
var ctx = $("#mycanvas");
var LineGraph = new Chart(ctx, {
type: 'line',
data: chartdata
});
},
error : function(data) {
}
});
});
<?php
//setting header to json
header('Content-Type: application/json');
//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '****');
define('DB_NAME', 'delta');
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
$SerialNumber = "00000000010";
//query to get data from the table
$query = 'SELECT heure, payload FROM reception WHERE Serial_number = "'.$SerialNumber.'" ORDER BY date DESC LIMIT 10';
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
?>
你在控制檯中看到什麼?? –
使用此代碼,我們具有圖表和SQL查詢,因爲PHP代碼中定義了$ SerialNumber。 但我試圖添加一個GET或一個POST來發送SerialNumber,但是每次請求都沒有在... – user46510
之後再做,你可以在我的答案中看到我的更改。我仍然沒有預期的結果:) – user46510