html - 如何在 HTML 表中显示带有分隔列的 SQL 查询结果
问题描述
现在,我将 SQL 查询作为“结果”,并将所有数据输出一大块。我通过在 line.innerHTML 行中添加 Category、OEM # 和 Price 来将其分开,但我无法弄清楚我需要做什么才能在 HTML 表中将其设置为每列分开。这是我现在正在使用的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="js/jquery-2.2.2.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet">
<title>AJAX Search Example</title>
<script>
function fetch() {
// (A) GET SEARCH TERM
var data = new FormData();
data.append('search', document.getElementById("search").value);
data.append('ajax', 1);
// (B) AJAX SEARCH REQUEST
var xhr = new XMLHttpRequest();
// (CHANGE1) USING ONREADYSTATECHNAGE INSTEAD OF ONLOAD
xhr.onreadystatechange = function (event) {
// (CHANGE2) we will check if ajax process has completed or not it goes from 1,2,3,4 means end.
if(this.readyState == 4){
// (CHANGE2) when ready state comes to 4 we then check what response status was it if it is 200 good else error.
if(this.status == 200){
// (CHANGE3) MOVED ALL YOUR CODE HERE
// (CHANGE4) we need to use responseText instead of response because JSON comes as string that is why we are parsing it to be converted into array
var results = JSON.parse(this.responseText);
//I have added just a measure to check what the out put is you can remove it latter. open dev console to get the result.
console.log(results);
wrapper = document.getElementById("results");
if (results.length > 0) {
wrapper.innerHTML = "";
// (CHANGE5) UPDATED data ref with results
for (i = 0; i < results.length; i++) {
let line = document.createElement("div");
//it is just as simple to create id only it must start with alphabet not number
line.id=`res${[i]}`;
//we created span tag to display price and this is what we will change. on that span we will create a data-price attribute which will hold original price and we will run calculations using that number
//BIG CHANGE
//BIG CHANGE
//since after parsing individual record will be in Js object so we dont need to access them like array results[i]['item']
//we access them with dot notation results[i].item
line.innerHTML = `Category:${results[i].category} - OEM #:${results[i].oemnumber} - Price:$<span data-price='${results[i].price}'>${results[i].price}</span>
select discount >>
<a href="#70">%70</a>
<a href="#60">%60</a>
<a href="#50">%50</a> <a href="#50">100%</a>`;
wrapper.appendChild(line);
}
// (CHANGE6) We moved event listeners here so any newly added elements will be updated.
//get all the links and apply event listener through loop
var links = document.querySelectorAll('a');
for ( ii = 0; ii < links.length; ii++) {
links[ii].addEventListener("click", function(event) {
//capture link value and get number to be converted to percentage
var percentage = event.target.innerText.match(/\d+/)[0]/100;
//capture the data-price which is within same div as anchor link
var pricetarget = event.target.parentElement.querySelector('[data-price]');
//get value of data-price
var actualprice= pricetarget.dataset.price;
//run math and chnage the value on display
pricetarget.innerHTML=(actualprice*percentage).toFixed(2);
});
}
} else { wrapper.innerHTML = "No results found"; }
} else {
//if reponse code is other ethan 200
alert('INTERNET DEAD OR AJAX FAILED ');
}
}
};
// (CHANGE7) We moved open event to end so everything is ready before it fires.
xhr.open('POST', "2-search.php");
xhr.send(data);
return false;
};
</script>
</head>
<body>
<!-- (A) SEARCH FORM -->
<form ID='myForm' onsubmit="return fetch();">
<h1>SEARCH FOR CATALYTIC CONVERTER</h1>
<input type="text" id="search" required/>
<input type="submit" value="Search"/>
</form>
<!-- (B) SEARCH RESULTS -->
<div id="results"></div>
</body>
</html>
如您所见,我将所有数据都放入结果中,然后显示在 div id="results" 中。我想要一张桌子,在一个插槽中有类别,在另一个插槽中有 oemnumber,在另一个插槽中有价格。任何关于我将如何去做的建议将不胜感激。谢谢你。
编辑:对不起,我忘了添加搜索脚本:
<?php
// (A) DATABASE CONFIG - CHANGE TO YOUR OWN!
define('DB_HOST', '');
define('DB_NAME', '');
define('DB_CHARSET', '');
define('DB_USER', '');
define('DB_PASSWORD', '');
// (B) CONNECT TO DATABASE
try {
$pdo = new PDO(
"mysql:host=".DB_HOST.";charset=".DB_CHARSET.";dbname=".DB_NAME,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]
);
} catch (Exception $ex) { exit($ex->getMessage()); }
// (C) SEARCH
$stmt = $pdo->prepare("SELECT * FROM `converter_prices` WHERE `category` LIKE ? OR `oemnumber` LIKE ? OR `price` LIKE ?");
$stmt->execute(["%".$_POST['search']."%", "%".$_POST['search']."%", "%".$_POST['search']."%"]);
$results = $stmt->fetchAll();
if (isset($_POST['ajax'])) { echo json_encode($results); }
解决方案
我正在尝试做一些我认为会是这样的事情,但我猜我只是没有正确编码:
line.innerHTML+= '<tr><td>' + `Category:${results[i].category} + '</td><td>' + OEM #:${results[i].oemnumber} + '</td><td>' + Price:$<span data-price='${results[i].price}'>${results[i].price}</span> + + '</td></tr>'
select discount >>
<a href="#70">%70</a>
<a href="#60">%60</a>
<a href="#50">%50</a> <a href="#50">100%</a>`;
wrapper.appendChild(line);
只是添加表格标签似乎不是正确的方法哈哈
推荐阅读
- shell - 如果在执行“sed -i --”时出错会发生什么情况,这是文件的更改
- highcharts - HighCharts navigator: how to disable the expand width icon on hover
- python - ggplot 到 R - 数据框 R
- file - 当 Folder.Files 返回不存在的文件夹时处理
- perl - 从 ip 命令获取 inet 的 Perl 脚本
- angular - *ngFor 停止在 IE 11 / Angular 4 上工作
- android - 依赖项顺序是否会在应用程序中进行任何更改?
- laravel - 在 Laravel 中使用数组过滤产品
- javascript - Firefox中图像加载缓慢
- windows - OpenGL 驱动程序更新 Windows 10