玩足球的杯子 · 小鹏接盘滴滴“造车”_财经_中国网· 1 年前 · |
憨厚的香烟 · 乐高DC沙赞:魔法与怪物_百度百科· 1 年前 · |
魁梧的打火机 · 宝马集团2022一季度中国区销量:交付208 ...· 1 年前 · |
绅士的剪刀 · 华人运通旗下高合汽车展示“中国实力”_手机凤凰网· 1 年前 · |
我有一个SQL搜索和结果页面,它为我提供了3列数据:类别、数字和价格。然而,结果却是一大块地返回。我希望能有一个下拉列表中的百分比,点击其中一个数字改变价格百分之那。试图找出我如何能够分开结果,这样我就可以让下拉列表改变价格。我想我需要在价格上加一个id,但我不知道该怎么做。我也想用PDO来做所有的事情,但是接下来我会想办法解决这个问题,现在我只想改变价格。下面是我正在使用的代码:
<!DOCTYPE html>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
<style>
.dropbtn {
background-color: #3498DB;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
.dropbtn:hover, .dropbtn:focus {
background-color: #2980B9;
.dropdown {
position: relative;
display: inline-block;
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
.dropdown a:hover {background-color: #ddd;}
.show {display: block;}
</style>
<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();
xhr.open('POST', "2-search.php");
xhr.onload = function () {
var results = JSON.parse(this.response),
wrapper = document.getElementById("results");
if (results.length > 0) {
wrapper.innerHTML = "";
for (let res of results) {
let line = document.createElement("div");
line.innerHTML = `Category:${res['category']} - OEM #:${res['oemnumber']} - Price:$${res['price']}`;
wrapper.appendChild(line);
} else { wrapper.innerHTML = "No results found"; }
xhr.send(data);
return false;
</script>
</head>
<!-- (A) SEARCH FORM -->
<form 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>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a href="#70">%70</a>
<a href="#60">%60</a>
<a href="#50">%50</a>
<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
</script>
</body>
</html>
所以现在所有的数据都是以“结果”的形式给出的,我在"line.innerHTML =
Category:${res['category']} - OEM #:${res['oemnumber']} - Price:$${res['price']}
“中添加了一些分隔符,至少给数据加上了标签,但是我希望能够将下拉列表中的javascript直接指向”价格“数据。如果能对此提供任何帮助,我们将不胜感激。这是php脚本,用于获取所需的数据:
<?php
// (A) DATABASE CONFIG - CHANGE TO YOUR OWN!
define('DB_HOST', '');
define('DB_NAME', '');
define('DB_CHARSET', 'utf8');
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); }
编辑:下面是我得到的结果:
我试图让它,所以如果我点击70%的下拉,它将改变价格列到70%的价值。
正如我所说,所有的结果似乎只是进入一个“结果”变量,我试图将其更改为类似于以下代码的内容:
<table>
$sql=$db->prepare('SELECT * FROM `converter_prices` WHERE `category` LIKE ? OR `oemnumber` LIKE ? OR `price` LIKE ?);
$sql->execute(array(':category'=>$_REQUEST[searchcategory]));
while ($row=$sql->fetch())
echo "<tr><td>$row[category]</td><td>$row[oemnumber]</td><td>$row[price]</td></tr>";
</table>
但我已经谷歌了几天,只是找不到正确的信息。我将谷歌DOM导航,看看这是否有帮助,谢谢。
发布于 2021-04-02 17:33:22
这是我的简约主义要旨。
,
来更改标签
在下面的假设中,数据是获取的结果。然后,我们在链接上创建了一个事件列表,该链接只需在给定的单击时运行该函数。事件列表是捕获event.target.innerText的,我们只运行简单的正则表达式,只从字符串中获取数字并运行乘法。
从我所了解的情况来看,你将如何处理这件事。
当然,这并不是最好的完美,但我会这样做。老实说,更多的是创造力,然后是技术性。
const data = [["apple","2.30"],["apple","4.5"]];
links = document.querySelectorAll('a');
for (i = 0; i < links.length; i++) {
links[i].addEventListener("click", function() {
percentage = event.target.innerText.match(/\d+/)[0]/100;
datanew =[];
for (i = 0; i < data.length; i++) {
datanew.push(data[i][0]);
datanew.push((data[i][1]*percentage).toFixed(2));
console.log(datanew)
}
<div class="dropdown">
<div id="myDropdown" class="dropdown-content">
<a href="#70">%70</a>
<a href="#60">%60</a>
<a href="#50">%50</a>
</div>
更新的ID示例
//this dummy data
const data = [["apple","2.30"],["orange","4.5"]];
//this where dummy data is displayed
wrapper = document.getElementById("results");
//loop over data to inject html
for (i = 0; i < data.length; i++) {
let line = document.createElement("div");
//it is just as simple to create id only it must start with alaphabet 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 orginial price and we will run claulcations using that number
line.innerHTML = `Category:${data[i][0]}
- Price:$<span data-price='${data[i][1]}'>${data[i][1]}</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);
//get all the links and apply event listner through loop
links = document.querySelectorAll('a');
for (i = 0; i < links.length; i++) {
links[i].addEventListener("click", function() {
//capture link value and get number to be converted to percetnage
percentage = event.target.innerText.match(/\d+/)[0]/100;
//capture the data-price which is within same div as anchor link
pricetarget = event.target.parentElement.querySelector('[data-price]');
//get value of data-price
actualprice= pricetarget.dataset.price;
//run math and chnage the value on display
pricetarget.innerHTML=(actualprice*percentage).toFixed(2);
}
<div id="results">
</div>
我在内部片段中添加了一些评论来解释发生了什么。我使用了数据集属性,在这种情况下非常方便。示例具有充分的交互性。
从提供的片段 更新了答案
<!DOCTYPE html>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
<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
xmlhttp.onreadystatechange = function () {
// (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 YIUR CODE HEREE
// (CHANGE4) we need to use responseText instead of response becuase 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 meassure to check what thte 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 alaphabet 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 orginial price and we will run claulcations using that number
//BIG CHANGE
//BIG CHANGE
//since after parsing invidual 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() {
//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>
<!-- (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>
玩足球的杯子 · 小鹏接盘滴滴“造车”_财经_中国网 1 年前 |
憨厚的香烟 · 乐高DC沙赞:魔法与怪物_百度百科 1 年前 |
绅士的剪刀 · 华人运通旗下高合汽车展示“中国实力”_手机凤凰网 1 年前 |