我打算使用googlecharts来绘制存储在本地数据库中的数据 - googlecharts代码也将存储在本地服务器上。我使用 XAMPP 创建了一个本地目录 ('http://http://127.0.0.1/)。在进入项目之前,我正在测试一个示例脚本(我从谷歌搜索中找到的),它从 json 文件(从 php 脚本调用)中获取数据,然后将其提供给 googlecharts 绘图函数。按照建议,这 3 个文件都存储在文件夹"C:''xampp''htdocs"中,但是当我在浏览器中加载页面时(http://127.0.0.1/test_php_long.html),页面显示为空白(在 Chrome、IE 和 Firefox 上)。当我运行一个谷歌图表脚本,将数据硬编码到HTML中时,它工作正常。我已经在网上寻找了几个小时,但还没有找到有效的解决方案。
这是主要的 html 文件 ('test_php_long.html'):
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.maxcdn.com/one//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
//fetchjson.php is a php script that will fetch the JSON data e generated using above php code
url: "fetchjson.php",
dataType:"json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.LineChart(document.getElementById('chart_flow'));
chart.draw(data, {width: 1200, height: 300, lineWidth: 1, pointSize: 1.3, pointWidth: 3});
}
</script>
</head>
<body>
<div id="chart_flow"></div>
</body>
</html>
这是php文件('fetchjson.php')
<html>
<head>
<title></title>
</head>
<body>
<?php
//Fill the ‘string’ variable with JSON data from file we used as json container populated by php //code: ‘flow.json’
$string = file_get_contents("flow.json");
//push JSON data out
echo $string;
?>
</body>
</html>
这是json文件('flow.json'):
{"cols":[{"id":","label":"Time","pattern":","type":"string"},{"id":","label":"Cache Hits","pattern":","type":"number"},{"id":","label":"非缓存命中","pattern":","type":"number"}],"rows":[{"c":[{"v":"2014-01-21 00:00:00"},{"v":2},{"v":23}]},{"c":[{"v":"2014-01-21 01:00:00"},{"v":2},{"v":52}]}, ... ,{"c":[{"v":"2014-01-23 01:00:00
"},{"v":0},{"v":34}]},]}谢谢!
您的问题可能与您的请求是跨源请求或至少被视为一次有关。据我所知,有两种方法可以解决此问题,要么通过在 PHP 脚本顶部添加以下行来允许跨源请求:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
虽然这可能不安全,并且 * 应替换为受信任域列表,但它现在应该可以解决您的问题,并且不会构成太大的安全威胁,因为您的应用将在 Intranet 中运行。
或者,您也可以通过将 json 对象包装在回调中来发出 jsonp 而不是 json:
echo $_GET['callback'] . '(' . json_encode($something_to_be_encoded) . ')';
不要忘记传递给 ajax 函数的 url 参数现在应该是:
http://myawesomescript.php?callback=?