我正在使用jquery将变量提供给php页面。
我希望php清除数据库中的表,根据变量加载新数据,查询新数据并回显结果。
问题是,每当我点击php页面时,php似乎都没有清除表格。当我将两组变量提供给php页面时,两个查询都会显示相同的结果。结果是我想要的结合。我做错了什么,有谁知道?
jquery的:
$.ajax({
url: "php/getTotals.php",
method: "POST",
data: {year : strYear, race: 'USP', type: strType},
success: function(data) {
var objPrez = jQuery.parseJSON(data);
fillTotal(objPrez, tbl_prezresults);
},
error: function(jxhr, statusText, err) {
console.log(statusText + " " + err);
}
});
//get gov totals
$.ajax({
url: "php/getTotals.php",
method: "POST",
data: {year : 2010, race: 'GOV', type: strType},
success: function(data) {
var objGov = jQuery.parseJSON(data);
fillTotal(objGov, tbl_govresults);
},
error: function(jxhr, statusText, err) {
console.log(statusText + " " + err);
}
});
getTotals.php:
require_once ('constants_test.php');
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit;
}
if( $_POST) {
$type = mysqli_real_escape_string($db, $_POST['type']);
$year = mysqli_real_escape_string($db, $_POST['year']);
$race = mysqli_real_escape_string($db, $_POST['race']);
$db->query("delete from elections_temp");
$data = array();
$q = "INSERT INTO elections_temp (SELECT * FROM elections where electionOffice = '" . $race . "' AND electionYear = '" . $year . "' AND electionType = '" . $type . "')";
$db->query($q);
$q_sums = "select firstName, lastName, party, sum(votes) as totvotes from elections_temp group by lastName order by totvotes desc";
$result = $db->query($q_sums);
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
//Add this row to the reply
$data[] = $row;
}
echo json_encode($data);
$db->close();
} else {
echo "You shouldn't be here.";
}
答案 0 :(得分:2)
您正在做的是以下内容:
2 ajax调用同时调用php脚本(可能延迟几毫秒)。
然后服务器执行您希望它执行的操作,但由于每个请求都创建/截断了临时表,因此会发生奇怪的事情。
以下是:
所以,因为你同时触发两个ajax调用,他们最终会在服务器上互相搞乱。
在request2启动之前,您的服务器可能还不够快,无法处理request1。
答案 1 :(得分:1)
我认为你不需要额外的桌子。你们都可以在一个sql
中完成$query = 'select firstName, lastName, party, sum(votes) as totvotes from elections
where electionOffice = "' . $race . '" AND electionYear = ' . $year . ' AND electionType = "' . $type . '"
group by lastName, firstName, party order by totvotes desc';
如果性能有问题,请为electionOffice,electionYear和electionType(所有在一个索引中)添加索引。