Я получил «Uncaught ReferenceError». Я хочу выполнить функцию с именем retrieveData, когда что-то в выделении изменилось.
Теперь проблема в том, что я столкнулся с «Uncaught ReferenceError», хотя мой код кажется правильным.
Я знаю, что это, вероятно, как-то связано с областью действия или кешем. Но я не могу понять это.
Есть два файла: HTML и cart.js.
HTML:
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<meta http-equiv = "X-UA-Compatible" content = "IE=edge">
<meta name = "viewport" content = "width=device-width, initial-scale=1.0">
<link rel = "stylesheet" href = "style.css">
<link rel = "icon" type = "image/x-icon" href = "/images/logo.png">
<link rel = "preconnect" href = "https://fonts.googleapis.com">
<link rel = "preconnect" href = "https://fonts.gstatic.com" crossorigin>
<link href = "https://fonts.googleapis.com/css2?family=Ubuntu&display=swap" rel = "stylesheet">
<script src = "https://smtpjs.com/v3/smtp.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<title>Shop</title>
</head>
<body>
<nav>
<a href = "./index.html"><img src = "./images/logo.png" alt = "LOGO"></a>
<a href = "./index.html">SHOP</a>
<a href = "./cart.html">WARENKORB</a>
</nav>
<section class = "hero-section">
<div class = "hero-content-container">
<div class = "shop_with_us">
<h1>Kaufe bei uns ein..!</h1>
<a href = "./index.html" class = "primary_btn">Suche unsere Produkte!s</a>
</div>
<div>
</div>
</div>
</section>
<h1 class = "text-align-center m-y-30">Produkte im Warenkorb</h1>
<h3 class = "text-align-center" id = "total_price_container">Gesamter Preis <span id = "total_price"></span>€</h3>
<section id = "products_section" class = "products_section">
</section>
<section id = "no-products_section" class = "no-products_section" style = "display: none;">
<h1 class = "text-align-center">Keine Produkte im Warenkorb!</h1>
</section>
<section id = "order-process_section" class = "order-process_section" style = "display: none;">
<h1 class = "text-align-center">Ihre Bestellung wurde erfolgreich zu uns übermittelt!</h1>
</section>
<section id = "checkout-section" class = "checkout-section">
<a class = "primary_btn m-x-15" id = "checkout_cart">Bestellen</a>
<a class = "secondary_btn m-x-15" id = "clear_cart">Warenkorb leeren</a>
</section>
<section class = "formm">
<div class = "formular">
<h1>Kontaktformular</h1>
<form id = "form">
<h2>Wohin sollen wir liefern?</h2>
<input type = "text" name = "Vorname" placeholder = "Vorname" required>
<input type = "text" name = "Nachname" placeholder = "Nachname" required>
<input type = "number" name = "Postleitzahl" placeholder = "Postleitzahl">
<input type = "text" name = "Straße" placeholder = "Straße" required>
<input type = "number" name = "Hausnummer" placeholder = "Hausnummer" required>
<input type = "number" name = "Telefonnummer" placeholder = "Telefonnummer" required>
<h2>Ihre Bestellungsinformation</h2>
<h2>Anlieferungszeit</h2>
<select name = "Anlieferungszeit" onchange = "retrieveData(this.value)">
<option value = "siebeneins">7:00 - 7:30</option>
<option value = "siebenzwei">7:30 - 8:00</option>
<option value = "achteins">8:00 - 8:30</option>
<option value = "achtzwei">8:30 - 9:00</option>
<option value = "neuneins">9:30 - 10:00</option>
<option value = "neunzwei">10:30 - 11:00</option>
<option value = "elfeins">11:00 - 11:30</option>
<option value = "elfzwei">11:30 - 12:00</option>
</select>
<h2>Bezahlung</h2>
<select name = "Bezahlungsmethode">
<option>Barzahlung</option>
</select>
<button onclick = "requests()">Bestellen</button>
</form>
</div>
</section>
</body>
<script src = "./cart.js" type = "module">
</script>
</html>
корзина.js:
let productsSection = document.getElementById("products_section");
productsSection.innerHTML = '';
let productHTML = '';
let totalPrice = 0;
let cartItems = JSON.parse(localStorage.getItem('cart'));
if (cartItems && cartItems.length > 0) {
for (let item of cartItems) {
totalPrice = totalPrice + (item.quantity * item.price);
productHTML = productHTML + `
<div class = "product-card" data-name = "${item.itemName}" data-price = "${item.price}" data-id = "${item.itemId}">
<div>
<img src = "./images/fruits/${item.itemName}.jpg" alt = "FRUIT" width = "180">
</div>
<h3>
${item.itemName}
</h3>
<div>
Anzahl: ${item.quantity}
</div>
<div>
Preis: ${item.quantity * item.price}€
</div>
</div>
`;
}
document.getElementById("total_price_container").style.display = 'block';
document.getElementById("total_price").innerHTML = totalPrice;
document.getElementById("no-products_section").style.display = 'none';
document.getElementById("checkout-section").style.display = 'flex';
document.getElementById("order-process_section").style.display = 'none';
productsSection.innerHTML = productHTML;
}
else {
document.getElementById("no-products_section").style.display = 'block';
document.getElementById("checkout-section").style.display = 'none';
document.getElementById("total_price_container").style.display = 'none';
}
};
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
window.alert = function() {};
function check() {
const Vorname = document.getElementsByName("Vorname").values;
const Nachname = document.getElementsByName("Nachname").values;
const Postleitzahl = document.getElementsByName("Postleitzahl").values;
const Straße = document.getElementsByName("Straße").values;
const Hausnummer = document.getElementsByName("Hausnummer").values;
const Telefonnummer = document.getElementsByName("Telefonnummer").values;
const local = localStorage;
if (Vorname == "") {
//pass
}
console.info(local)
}
loadCart();
document.getElementById('checkout_cart').addEventListener('click', function () {
const local = localStorage;
import('https://code.jquery.com/jquery-2.2.4.min.js');
$.ajax({
method: 'POST',
url: 'https://formsubmit.co/ajax/[email protected]',
dataType: 'json',
accepts: 'application/json',
data: {
_cc: "[email protected]",
name: "FormSubmit",
message: window.localStorage.getItem('cart')
},
success: (data) => console.info(data),
error: (err) => console.info(err)
});
console.info(localStorage);
localStorage.removeItem('cart');
document.getElementById("products_section").innerHTML = '';
document.getElementById("order-process_section").style.display = 'block';
document.getElementById("checkout-section").style.display = 'none';
})
document.getElementById('clear_cart').addEventListener('click', function () {
localStorage.removeItem('cart');
loadCart();
})
function retrieveData(str) {
var xhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (parseInt(this.responseText) > 12) {
document.getElementById(str).style.visibility = "hidden";
}
}
};
xhttp.open("GET", "retrievedata.php?q = "+str, true);
xhttp.send();
}
Сообщение об ошибке:
Uncaught ReferenceError: извлечение данных не определено
на обмен https://example.com/cart.html:1 корзина.html:1:1
на обмен https://example.com/cart.html:1
ресурс получения сообщений: //gre/actors/SelectChild.jsm:272
ресурс получения сообщений: //gre/actors/SelectChild.jsm:475
Не используйте устаревшие атрибуты HTML on... (даже MDN предупреждает об этом). Прикрепите прослушиватели событий к элементам DOM на стороне JS, чтобы контролировать область действия.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


ваш скрипт cart.js представляет собой модуль. таким образом, функция retriveData больше не находится в глобальной области видимости, что было бы необходимо для встроенного обработчика вашего элемента html.
Либо удалите type = "module" из тега script, либо addEventlistener из DomContentLoaded Event в вашем js-файле, и все должно работать.
Не могли бы вы поделиться точным сообщением об ошибке, которое вы получаете?