我有一个问题,为了改变页面内容,我必须接收用户输入。我想通过弹出式表单完成此操作。单击弹出式菜单上的“提交”按钮后,我想将表单输入发送到
php
文件,我连接到数据库,并通过JSON将检索到的信息发送到
js
文件,其中我使用
$.post()
实现这一切的方法。问题是,由于页面内容在没有重新加载的情况下被更改,我被重定向到一个页面
http://localhost/statistics.php?major=KN&year=2011
但我想留在页面上
http://localhost/statistics.php
这就是我首先使用AJAX的原因。
major=KN
&
year=2011
是我的POST参数。提交弹出表单后,是否可以更改页面内容?如有任何帮助,将不胜感激。
以下是我认为可能与解决问题相关的代码:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="ch/Chart.js"></script>
<script src="js/statistics_js.js"></script>
</head>
<body>
<div id="content">
<div id="abc">
<div id="popupContact">
<form id="form1" name="form1">
<img class="close" src="images/3.png" onclick ="div_hide_group_popup()">
<h2>Fill the form</h2>
<hr>
<input name="major" placeholder="Major" type="text">
<input name="year" placeholder="Year" type="number">
<button id="submit1">Submit</button>
</form>
</div>
</div>
<div id="page">
<canvas id="myChart"></canvas>
</div>
<aside>
<h3>Compare</h3>
<ul>
<li id="group"><a href="#">groups</a></li>
</ul>
</aside>
</div>
</body>
</html>
这个
js/statistics_js.js
文件:
function error(){
alert('Error!');
}
$(document).ready(function(){
$('#group').on('click', function(e) {
e.preventDefault();
document.getElementById('abc').style.display = "block";
});
});
$(document).ready(function(){
$("#submit1").click( function() {
$.post( "http://localhost/group_sort.php", $("#form1").serialize(), "JSON").done(function(data) {
//This should use the Chart.js library to draw a chart on the canvas with the data retrieved from the server.
var barChartData = {
labels : data.groups,
datasets : [
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,0.8)",
highlightFill : "rgba(151,187,205,0.75)",
highlightStroke : "rgba(151,187,205,1)",
data : data.groups_total_points
}
]
}
var ctx = document.getElementById("myChart").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
responsive : true
});
}).error(error);
});
});
function div_hide_group_popup(){
document.getElementById('abc').style.display = "none";
}
我的
group_sort.php
:
<?php
require "config.php";
try {
$conn = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
}
catch(PDOException $e) {
die("Database connection could not be established.");
}
$conn->exec("SET NAMES UTF8");
$major = $_POST['major'];
$year = $_POST['year'];
$sql = "SELECT result.group, SUM(result.grade) AS group_total_points
FROM (
SELECT *
FROM students AS s
INNER JOIN points AS p
ON s.fn = p.student_fn
) result
WHERE result.major = '$major' AND result.year = '$year'
GROUP BY result.group
ORDER BY group_total_points DESC";
$query = $conn->query($sql);
if($query->rowCount() > 0) {
$data = array (
"groups" => [],
"groups_total_points" => [],
);
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$data["groups"][] = $row["group"];
$data["groups_total_points"][] = $row["group_total_points"];
}
echo json_encode($data);
}
else {
echo mysql_error();
}
$conn = null;
?>