将JS变量传递给PHP Ajax

时间:2017-09-02 13:05:10

标签: javascript php ajax

不可能在这段变量中走出来我尝试了很多东西......但这通常并不复杂......

我想传递一个变量:JS中的SerialNumberJS(我通过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);
?>

1 个答案:

答案 0 :(得分:1)

要获取PHP文件中的序列号,您需要在ajax请求的数据元素中传递它:

$.ajax({
        url : "graphdata.php",
        type : "GET",
        data: {
            'SerialNumberJS' : SerialNumberJS // add other if needed
        },
        success : function(data){
            // your code....
        }
    });