php - 如何将数据从 php 文件导入到 javascript 变量

标签 php javascript jquery mysql ajax

我将从以下问题开始:我有一个查询 MySql 数据库的 php 文件,我想将结果放入一个 javascript 数组中,以便我可以绘制它(使用 jQuery 的 flot)。有人知道该怎么做吗?

到目前为止我所做的工作:

  1. 我有一个非常好的 jQuery-flot 代码,可以绘制图表。请注意,此代码中此问题最重要的变量是“data1”。
  2. AJAX(带有 php 文件)打印来自 mysql 数据库的数据

我想将数据库中的数据(时间和数据)放入“data1”变量(在 jquery-flot 代码中),但我找不到将 php 文件结果与data1 变量。

jQuery-flot 图表绘制代码(请注意'data1'变量):

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>
<head>
    <title>Flot Example</title>
    <script language="javascript" type="text/javascript" src="js/flot/jquery.js"></script>
    <script language="javascript" type="text/javascript" src="js/flot/jquery.flot.js"></script>
    <script language="javascript" type="text/javascript" src="js/flot/jquery.flot.selection.js"></script>
</head>
<body>
    <h1>Flot Examples</h1>s
    <div id="placeholder" style="width:600px;height:300px"></div>
    <div id="overview" style="width:160px;height:100px"></div>
    <script type="text/javascript">
     /*Show Tooltip*/
     function showTooltip(x, y, contents) {
     $('<div id="tooltip">' + contents + '</div>').css({
         position: 'absolute',
         display: 'none',
         top: y + 5,
         left: x + 5,
         border: '1px solid #fdd',
         padding: '2px',
         'background-color': '#fee',
         opacity: 0.80
     }).appendTo("body").fadeIn(200);
 }

 //End of Tooltip    
 var data, data1, options, optionsOverview, chart, overview;
 var data2 = [],
 data3 = [];
 data1 = [
     [1, 4],
     [2, 5],
     [3, 6],
     [4, 9],
     [5, 7],
     [6, 6],
     [7, 2],
     [8, 1],
     [9, 3]
 ];

 for (var i = 1; i < 10; i++) {
     data2.push([i, i * 2])
 }

 for (var i = 1; i < 10; i++) {
     data3.push([i, 10 * Math.random()])
 }

 data = [{
     data: data1,
     label: "fixed",
     lines: {
         show: true
     }
 }, {
     data: data2,
     label: "linear",
     lines: {
         show: true
     },
     points: {
         show: true
     }
 }, {
     data: data3,
     label: "random",
     bars: {
         show: true,
         barWidth: 0.5
     }
 }];

 options = {
     legend: {
         position: "nw"
     },
     grid: {
         clickable: true,
         hoverable: true
     }
 };

 //SELECTION 
 optionsOverview = {
     legend: {
         show: false
     },
     selection: {
         mode: "xy"
     }
 };

 $(document).ready(function () {
     chart = $.plot($("#placeholder"), data, options);
     //SELECTION 
     overview = $.plot($("#overview"), data, optionsOverview);
 });

 /*SELECTION*/
 $("#overview").bind("plotselected", function (event, ranges) {
     chart.setSelection(ranges);
 });

 $("#placeholder").bind("plotselected", function (event, ranges) {
 if (ranges.xaxis.to - ranges.xaxis.from < 0.00001) {
     ranges.xaxis.to = ranges.xaxis.from + 0.00001;
 }
 if (ranges.yaxis.to - ranges.yaxis.from < 0.00001) {
     ranges.yaxis.to = ranges.yaxis.from + 0.00001;
 }
 plot = $.plot("#placeholder", data,
     $.extend(true, {}, options, {
         xaxis: {
             min: ranges.xaxis.from,
             max: ranges.xaxis.to
         },
         yaxis: {
             min: ranges.yaxis.from,
             max: ranges.yaxis.to
         }
     })
 );
 overview.setSelection(ranges, true);

 });
 //End of Selection
 /*Show Tooltip*/

 $("#placeholder").bind("plothover", function (event, pos, item) {
     $("#tooltip").remove();
     if (item) {
         var x = item.datapoint[0].toFixed(2),
         y = item.datapoint[1].toFixed(2);
        showTooltip(item.pageX, item.pageY, item.series.label + " of " + x + " - " + y);
     }
 });
//End of Tooltip
</script>
    <br /><br /><br />

</body>
</html>

另一方面,我有一个 MySQL 数据库:

mysql> select * from example5;
+------+------+
| time | data |
+------+------+
|    1 |    1 |
|    1 |    2 |
|    2 |    3 |
|    3 |    6 |
|    4 |    9 |
|    5 |   10 |
|    6 |   15 |
|    7 |   20 |
+------+------+
8 rows in set (0.00 sec)

我使用 ajax/php 文件访问它: index.html:

<html>
<head>
<script>
function showUser(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    }
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", "getdata.php?q=" + str, true);
    xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select Time:</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="4">5</option>
<option value="4">6</option>
<option value="4">7</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>

</body>
</html>

和getdata.php:

<?php
$q=$_GET["q"];


$con = mysqli_connect('localhost','root','12345678','test');
if (!$con)
  {
  die('Could not connect: ' . mysqli_error($con));
  }

mysqli_select_db($con,"test");
$sql="SELECT * FROM example5 WHERE time = '".$q."'";

$result = mysqli_query($con,$sql);

echo "<table border='1'>
<tr>
<th>Time</th>
<th>Data</th>
</tr>";

while($row = mysqli_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['time'] . "</td>";
  echo "<td>" . $row['data'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysqli_close($con);
?>

感谢您的帮助, 诺姆

最佳答案

在 PHP 和 Javascript 之间进行通信的一种简单方法是 JSON。 PHP 可以轻松地对 JSON 中的数组进行编码/解码,而 JS 可以对对象进行同样的操作。您可以尝试以下操作:

在您的 PHP 脚本中,返回一个包含您的数据的 JSON 数组:

<?php
    $q=$_GET["q"];
    $con = mysqli_connect('localhost','root','12345678','test');
    if (!$con)
    {
        die('Could not connect: ' . mysqli_error($con));
    }

    mysqli_select_db($con,"test");
    $sql="SELECT * FROM example5 WHERE time = '".$q."'";

    $result = mysqli_query($con,$sql);

    $returnArray = array();
    while($row = mysqli_fetch_array($result))
    {
         $returnArray[] = array($row['time'], $row['data']);
    }
    echo json_encode($returnArray);
    mysqli_close($con);
?>

在您的 Javascript 中,像这样创建一个 AJAX 调用(我使用的是 JQuery):

function retrieveResults(str){
jQuery.ajax({
        type: 'GET',
        url: "getdata.php",
        data: {
            q: str,
        }, 
        success: function(data, textStatus, jqXHR) {
            var json = $.parseJSON(data);
                $.each(json, function(index, value) {
                    data1.push(value); // Not sure if it is correct, you might need to do some changes, but this is for the global idea 
                }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log('An error occurred:'+errorThrown);
        }
    });
}

关于php - 如何将数据从 php 文件导入到 javascript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18182614/

相关文章:

php - 我想使用 PHP 和 AJAX 为我的网站创建一个菜单编辑器

PHP 得到警告和错误信息?

javascript - 使用选择器进行完整 ID 搜索

javascript - jQuery 是否为每个具有 id 的元素创建一个全局范围的对象?

javascript - jQuery mobile .changePage 无法正常工作

php - 在 PHP 5.1 中添加月份的准确方法?

php - Linux 和 Windows 进程之间的 IPC

javascript - 重新创建 Medium 的图像淡入淡出滚动效果

javascript - 定期更新和渲染来自 Flask 的值

javascript - 如何在 jquery 中捕获 cmd + enter 事件