0
我想完成以下函數,它通過AJAX將值作爲參數發送給查詢,後者將在用戶的屏幕上輸出報表結果而不重新加載。Node.js - 如何通過AJAX傳遞多個MySQL查詢參數
如果我有一個參數只工作(datereport:「2017年6月21日」)它工作正常,我也得到了同樣的頁面結果,而無需重新加載它。
查看網址是localhost/reports
然而,當我嘗試用第二個值的工作像currencyreport
沒有得到它,直到AJAX功能,當然還有後端。
EJS
<input id="datereport" class="form-control" name="datereport" value="2017-06-21">
<input id="currencyreport" class="form-control" name="currencyreport" value="GBP">
<input type="button" value="Search" class="btn btn-info mr-1" onClick="searchReport([document.getElementById('datereport').value,document.getElementById('currencyreport').value])">
AJAX函數從後端發送和獲取值到/
function searchReport(datereport, currencyreport) {
console.log(datereport) // it outputs both datereport,currencyreport values instead of the first one only ["2017-06-21","GBP"]
console.log(currencyreport) // it outputs undefined
$.ajax({
url: "/reports",
type: "get",
data: $("#report-form").serialize(),
success: function(res) {
$.post("/reportsdate/" + data, function(data) {
// it builds GET /reports?datereport=2017-06-21¤cyreport=GBP
ok(data);
});
return false;
},
error: function(xhr, status, error) {
// error stuff
}
});
}
// The part which takes the backend results and output in the same page without reloading
function ok(datares) {
document.getElementById("results").innerHTML = Object.values(datares.data[0])
}
後端
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var url = require('url');
router.use(bodyParser.urlencoded({ extended: true }));
router.use(function(req, res, next) {
console.log(req.method, req.url);
next();
});
var reports = router.route('/reports');
var reportsdate = router.route('/reportsdate');
router.get('/reportsdate', function(req, res) {
res.render('reports');
});
router.get('/reports', function(req, res) {
res.render('reports');
});
reportsdate.post(function(req, res, next) {
datereport = req.query.datereport;
currencyreport = req.query.currencyreport;
req.getConnection(function(err, conn) {
if (err) return next("Cannot Connect");
var queryString = "SELECT SUM(total_profit) AS fee_total FROM transactions WHERE date_created = ?";
var queryParams = [];
queryParams.push(datereport);
if(currencyreport){
queryString += ' AND currency = ? ';
queryParams.push(currencyreport);
}
var query = conn.query(queryString, queryParams, function(err, rows) {
if (err) {
console.log(err);
return next(err);
}
var ab = {data: rows};
console.log('hohohoho ' + JSON.stringify(ab));
res.send(ab)
});
});
});
router.get('/reports', function(req, res) {
res.render('reports', {data: ab});
});
謝謝,這的確是第一個獲取值直到AJAX函數的問題。然而,值仍然不能到達後端部分(mysql查詢參數),所以輸出的查詢結果可以發回到前端。 – Vasikos