我有两个单独的代码: 1. 一个表单在按钮单击时显示数据库的内容 (form.php) 2. 另一个 php 页面显示图表到 div 中,在加载时从 mysql 数据库中检索内容。(graph.php)
我是ajax的新手。我试图在另一个 php 页面的(form.php)div 上显示图表,其代码存在于 graph.php 中。
问题是graph.php,它显示加载事件的图表使用同一页面本身(graph.php)中存在的div id来显示图表。如何在 form.php 中的 div 中加载此页面
表单.php
<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","graph.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input type="submit"onclick="showUser(this.value)"/>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
另一个从 db 加载数据并使用谷歌图表 API 显示图表的页面是 graph.php:
<?php
$q=$_GET["q"];
$mysqli =mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$result = $mysqli->query('SELECT * FROM new_temp');
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'ind_type', 'type' => 'string'),
array('label' => 'sum', 'type' => 'number')
);
/* Extract the information from $result */
foreach($result as $r) {
$temp = array();
$temp[] = array('v' => (string) $r['ind_type']);
$temp[] = array('v' => (int) $r['sum']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'Index analysis',
is3D: 'true',
width: 800,
height: 600
};
var chart = new google.visualization.PieChart(document.getElementById('txtHint'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="txtHint"></div>
</body>
</html>