我一直在使用 Flask、HTML 和 javascript。我必須為學校重新創建一個披薩網站。幾乎一切都很好,我知道如何通過 html 和 python 訪問其他頁面。但在某些時候,我將使用一個運行 javascript 腳本的按鈕,這很好。但是當我嘗試通過燒瓶或通過帶有行(示例)的html重定向它來更改站點時:`
<li><a href={{ url_for('store') }}>Menu</a></li>
`
它不起作用。我還嘗試將其重定向到假定的下一個站點,因為我確實設定了一個接收 json 包的站點,并且所有這些都可以正常作業。但唯一不起作用的行是重定向行。我收到訊息:“GET /payment HTTP/1.1”200
現在我明白了,如果我收到訊息,那就意味著一切順利。然而我想要發生的事情并沒有發生。所以我缺乏知識和錯誤的思維方式阻礙了我。
我希望我能在這里得到答案。同樣,在我想使用使用 javascript 的按鈕更改站點之前,任何其他訪問其他站點的方式都進展順利
Javascript檔案`
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready)
} else {
ready()
}
function ready() {
var removeCartItemButtons = document.getElementsByClassName('btn-danger')
for (var i = 0; i < removeCartItemButtons.length; i ) {
var button = removeCartItemButtons[i]
button.addEventListener('click', removeCartItem)
}
var quantityInputs = document.getElementsByClassName('cart-quantity-input')
for (var i = 0; i < quantityInputs.length; i ) {
var input = quantityInputs[i]
input.addEventListener('change', quantityChanged)
}
var addToCartButtons = document.getElementsByClassName('shop-item-button')
for (var i = 0; i < addToCartButtons.length; i ) {
var button = addToCartButtons[i]
button.addEventListener('click', addToCartClicked)
}
document.getElementsByClassName('btn-purchase')[0].addEventListener('click', purchaseClicked)
}
function purchaseClicked() {
alert('Thank you for your purchase')
var cartItems = document.getElementsByClassName('cart-items')[0]
while (cartItems.hasChildNodes()) {
cartItems.removeChild(cartItems.firstChild)
}
updateCartTotal()
}
function removeCartItem(event) {
var buttonClicked = event.target
buttonClicked.parentElement.parentElement.remove()
updateCartTotal()
}
function quantityChanged(event) {
var input = event.target
if (isNaN(input.value) || input.value <= 0) {
input.value = 1
}
updateCartTotal()
}
function addToCartClicked(event) {
var button = event.target
var shopItem = button.parentElement.parentElement
var title = shopItem.getElementsByClassName('shop-item-title')[0].innerText
var price = shopItem.getElementsByClassName('shop-item-price')[0].innerText
var imageSrc = shopItem.getElementsByClassName('shop-item-image')[0].src
addItemToCart(title, price, imageSrc)
updateCartTotal()
}
function addItemToCart(title, price, imageSrc) {
var cartRow = document.createElement('div')
cartRow.classList.add('cart-row')
var cartItems = document.getElementsByClassName('cart-items')[0]
var cartItemNames = cartItems.getElementsByClassName('cart-item-title')
for (var i = 0; i < cartItemNames.length; i ) {
if (cartItemNames[i].innerText == title) {
alert('This item is already added to the cart')
return
}
}
var cartRowContents = `
<div class="cart-item cart-column">
<img class="cart-item-image" src="${imageSrc}" width="100" height="100">
<span class="cart-item-title">${title}</span>
</div>
<span class="cart-price cart-column">${price}</span>
<div class="cart-quantity cart-column">
<input class="cart-quantity-input" type="number" value="1">
<button class="btn btn-danger" type="button">REMOVE</button>
</div>`
cartRow.innerHTML = cartRowContents
cartItems.append(cartRow)
cartRow.getElementsByClassName('btn-danger')[0].addEventListener('click', removeCartItem)
cartRow.getElementsByClassName('cart-quantity-input')[0].addEventListener('change', quantityChanged)
}
function updateCartTotal() {
var cartItemContainer = document.getElementsByClassName('cart-items')[0]
var cartRows = cartItemContainer.getElementsByClassName('cart-row')
var total = 0
for (var i = 0; i < cartRows.length; i ) {
var cartRow = cartRows[i]
var priceElement = cartRow.getElementsByClassName('cart-price')[0]
var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
var price = parseFloat(priceElement.innerText.replace('$', ''))
var quantity = quantityElement.value
total = total (price * quantity)
}
total = Math.round(total * 100) / 100
document.getElementsByClassName('cart-total-price')[0].innerText = '$' total
}
`
HTML 檔案`
<!DOCTYPE html>
<html>
<head>
<title>Mario and Luigi's | Menu</title>
<link href="http://fonts.cdnfonts.com/css/italiana" href="{{ url_for('static', filename='css/styles.css') }}">
<meta name="description" content="This is the description">
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
<script src="{{ url_for('static', filename='JS/store.js') }}" async></script>
</head>
<body>
<header class="main-header">
<nav class="main-nav nav">
<ul>
<li><a href={{ url_for('homepage') }}>Home page</a></li>
<li><a href={{ url_for('store') }}>Menu</a></li>
<li><a href={{ url_for('about') }}>About us</a></li>
</ul>
</nav>
<h1 class="Restaurant-name Restaurant-name-large">Mario and Luigi's</h1>
</header>
<section class="container content-section">
<h2 class="section-header">Popular Pizzas</h2>
<div class="shop-items">
<div class="shop-item">
<span class="shop-item-title">Margherita</span>
<img class="shop-item-image" src="{{ pizzaMagherita }}">
<div class="shop-item-details">
<span class="shop-item-price">$12.99</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
<div class="shop-item">
<span class="shop-item-title">Pepperoni</span>
<img class="shop-item-image" src="{{ pizzaPepperoni }}">
<div class="shop-item-details">
<span class="shop-item-price">$14.99</span>
<button class="btn btn-primary shop-item-button"type="button">ADD TO CART</button>
</div>
</div>
<div class="shop-item">
<span class="shop-item-title">Prosciutto E Funghi</span>
<img class="shop-item-image" src="{{ pizzaProsciutto }}">
<div class="shop-item-details">
<span class="shop-item-price">$15.99</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
<div class="shop-item">
<span class="shop-item-title">Quattro Stagioni</span>
<img class="shop-item-image" src="{{ pizzaQuattros }}">
<div class="shop-item-details">
<span class="shop-item-price">$17.99</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
</div>
</section>
<section class="container content-section">
<h2 class="section-header">Hot Deals</h2>
<div class="shop-items">
<div class="shop-item">
<span class="shop-item-title">Star Carlos</span>
<img class="shop-item-image" src="{{ pizzaStarCarlos }}">
<div class="shop-item-details">
<span class="shop-item-price">$13.99</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
<div class="shop-item">
<span class="shop-item-title">Nino Bellisimo</span>
<img class="shop-item-image" src="{{ PizzaNinoBel }}">
<div class="shop-item-details">
<span class="shop-item-price">$15.99</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
<div class="shop-item">
<span class="shop-item-title">Marinara </span>
<img class="shop-item-image" src="{{ pizzaMarinara }}">
<div class="shop-item-details">
<span class="shop-item-price">$10.99</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
</div>
</section>
<section class="container content-section">
<h2 class="section-header">Luigi's Specials</h2>
<div class="shop-items">
<div class="shop-item">
<span class="shop-item-title">Luigi's Burger Pizza</span>
<img class="shop-item-image" src="{{ pizzaBurger }}">
<div class="shop-item-details">
<span class="shop-item-price">$19.99</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
<div class="shop-item">
<span class="shop-item-title">Luigi's Exotic Pizza</span>
<img class="shop-item-image" src="{{ pizzaExotic }}">
<div class="shop-item-details">
<span class="shop-item-price">$6.99</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
</div>
</section>
<section class="container content-section">
<h2 class="section-header">CART</h2>
<div class="cart-row">
<span class="cart-item cart-header cart-column">ITEM</span>
<span class="cart-price cart-header cart-column">PRICE</span>
<span class="cart-quantity cart-header cart-column">QUANTITY</span>
</div>
<div class="cart-items">
</div>
<div class="cart-total">
<strong class="cart-total-title">Total</strong>
<span class="cart-total-price">$0</span>
</div>
<button class="btn btn-primary btn-purchase" type="button" onclick='myFunction();' >PURCHASE</button>
</section>
<footer>
<header class="main-header">
<nav class="main-nav nav">
<ul>
<li><a href={{ url_for('homepage') }}>Home page</a></li>
<li><a href={{ url_for('store') }}>Menu</a></li>
<li><a href={{ url_for('about') }}>About us</a></li>
</ul>
</nav>
<h1 class="Restaurant-name Restaurant-name-large">Mario and Luigi's</h1>
</header>
</footer>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
function myFunction() {
const price = document.getElementsByClassName('cart-total-price')[0].innerText;
console.log(price)
const dict_values = {price}
const s = JSON.stringify(dict_values);
console.log(s)
$.ajax({
url:"/test",
type:"POST",
contentType: "application/json",
data: JSON.stringify(s)});
}
</script>
</body>
</html>
`
帶有燒瓶的python檔案`
import json
from operator import truth
from flask import Flask, jsonify, redirect, request, render_template, template_rendered, session, url_for
from datetime import timedelta
import os
app = Flask(__name__)
app.secret_key = "fresku"
app.permanent_session_lifetime = timedelta(hours=1)
images_folder = os.path.join('static', 'Images')
app.config['UPLOAD_FOLDER'] = images_folder
price = 0
@app.route("/", methods=["POST", "GET"])
def homepage():
if request.method == "POST":
session.permanent = truth
user = request.form["nm"]
session["user"] = user
return redirect (url_for("store"))
else:
if "user" in session:
return redirect (url_for("store"))
return render_template('index.html')
@app.route("/logout")
def logout():
session.pop("user", None)
return redirect(url_for("homepage"))
@app.route("/store", methods=["POST", "GET"])
def store():
MagheritaPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'MargheritaPizza.jpg')
BurgerPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'BurgerPizza.jpg')
ExoticPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'ExoticPizza.jpg')
MarinaraPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'MarinaraPizza.jpg')
NinoBelPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'NinoBelPizza.jpg')
PepperoniPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'PepperoniPizza.jpg')
ProsciuttoPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'ProsciuttoPizza.jpg')
QuattrosPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'QuattrosPizza.jpg')
StarCarlosPizzaPic = os.path.join(app.config['UPLOAD_FOLDER'], 'StarCarlosPizza.jpg')
return render_template("store.html",
pizzaMagherita = MagheritaPizzaPic,
pizzaBurger = BurgerPizzaPic,
pizzaExotic = ExoticPizzaPic,
pizzaMarinara = MarinaraPizzaPic,
PizzaNinoBel = NinoBelPizzaPic,
pizzaPepperoni = PepperoniPizzaPic,
pizzaProsciutto = ProsciuttoPizzaPic,
pizzaQuattros = QuattrosPizzaPic,
pizzaStarCarlos = StarCarlosPizzaPic)
@app.route("/about")
def about():
return render_template("about.html")
@app.route("/test", methods=['POST', 'GET'])
def test():
global price
output = request.get_json()
result = json.loads(output)
#this is a dict type
print(result['price'])
price = result['price']
return redirect (url_for("payment"))
@app.route("/customize")
def customize():
logoPic = os.path.join(app.config['UPLOAD_FOLDER'], 'logo.jpg')
return render_template("custom_page.html",
logo = logoPic)
@app.route("/payment", methods=['POST', 'GET'])
def payment():
global price
return render_template("pay_page.html",
customerPay = price)
@app.route("/track_order")
def tracker():
return render_template("tracker_page.html")
`
我嘗試使用 ` 行通過服務器重定向它
return redirect (url_for("payment"))
并嘗試使用 html 內的行更改頁面
<li><a href={{ url_for('store') }}>Menu</a></li>
鏈接不會改變,即使它必須改變。但我也沒有收到錯誤訊息
uj5u.com熱心網友回復:
您需要將您的 href URL 用引號括起來,如下所示:
<li><a href="{{ url_for('store') }}">Menu</a></li>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/525187.html
標籤:Pythonhtml烧瓶
上一篇:誰能幫我解決這個問題?
