【发布时间】:2018-04-10 22:25:50
【问题描述】:
第一次提问:)
所以我有一个 HTML 页面,它从下拉菜单中获取数值并尝试使用它们来填充 Google 图表。这是使用 Javascript 函数完成的
function displayChart() {
var sct = document.getElementById("sct").value;
var ind = document.getElementById("ind").value;
var spc = document.getElementById("spc").value;
var sub = document.getElementById("sub").value;
if ( sub == "" ) {
document.getElementById( "myChart" ).innerHTML = "";
return;
} else {
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 ( this.readyState == 4 && this.status == 200 ) {
document.getElementById( "myChart" ).innerHTML = this.responseText;
}
};
xmlhttp.open( "GET", "chart.php?sct="+sct+"&ind="+ind+"&spc="+spc+"&sub="+sub, true );
xmlhttp.send();
}
}
这链接到一个 php 页面,该页面使用作为 MySQL 语句的一部分传递的变量:
$sct = intval[ 'sct' ];
...
...
...
function get_transactions() {
$purchases_sql_stmt = "SELECT CT_Purchases FROM Company_Transactions WHERE CT_Sector = $sct && CT_Industry = $ind && CT_Specoality = $spc && CT_Subspeciality = $sub";
}
我希望这个函数会在 PHP 文件中的脚本标记中调用,该文件包含创建 Google 图表所需的所有代码。
// Load the Visualization API and the piechart package.
google.charts.load( 'current', {
'packages': [ 'bar' ]
} );
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback( drawChart );
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = <?php echo json_encode( get_transactions() ); ?>;
var years = data[ 0 ];
var sales = data[ 1 ];
var purchases = data[ 2 ];
var tableArray = new Array();
for ( var i = 0; i < data[ 0 ].length; i++ ) {
tableArray.push( new Array() )
tableArray[ i ].push( [ Number( years[ i ] ), Number( sales[ i ] ), Number( purchases[ i ] ) ] )
}
var table = new google.visualization.DataTable();
table.addColumn( 'number', 'Year' );
table.addColumn( 'number', 'Sales' );
table.addColumn( 'number', 'Purchases' );
for ( var i = 0; i < tableArray.length; i++ ) {
table.addRow( tableArray[ i ][ 0 ], tableArray[ i ][ 1 ], tableArray[ i ][ 2 ] );
}
// Set chart options
var options = {
chart: {
title: 'Sales for Mens Clothing Stores',
},
hAxis: {
format: ''
},
width: 640,
height: 320
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.charts.Bar( document.getElementById( "columnchart_material" ) );
chart.draw( table, google.charts.Bar.convertOptions( options ) );
}
问题是,我已经尝试在一个单独的 PHP 页面上使用这个确切的代码,其中 MySQL 语句中的值已被硬编码以创建结果,并且整个过程完美运行。我还能够确定调用页面不是问题,因为我已经能够在其中执行回声。问题似乎是在使用 xmlhttp.open() 调用页面后,chart.php 中的脚本标签被忽略了。是否有特定原因,如果是,我该如何解决?非常感谢:)
【问题讨论】:
-
如果他对值进行硬编码,OP 的函数起作用的原因是因为他没有在函数内部全局化任何 get 变量(或将它们作为参数传递)并且没有在开始时正确声明变量。我在下面的回答显示了如何解决这三个问题。首先修复这些问题至关重要,这样我们才能在之后正确调试任何问题......但这些问题不应被忽视。
标签: javascript php html xml xmlhttprequest