Javascript 使用Django为AJAX提取多个HTML DOM元素时出现问题
我正在尝试在一个web应用程序上实现一个功能,其中我有一个比萨菜单,并且每张卡上列出的价格(功能来自Bootstrap)根据所选比萨的风格(普通/西西里)、大小(小/大)和名称(奶酪/特色)动态更新。我正在使用一个循环来创建所有的卡片,方法是在后端使用ORM查询数据库,这将获取餐馆老板添加的所有现有比萨饼,并为每个比萨饼创建一个菜单项。然后,我打算提取每个比萨饼的名称、样式和尺寸选择,并在实现用户购买比萨饼的结账功能之前,使用AJAX在卡片的价格区域中动态呈现特定类型比萨饼的价格。问题主要在于我不确定如何提取名称、样式和大小选择,因为这些卡是使用模板循环实现的,而且我认为在我的AJAX/后端中有一些小错误。但我怀疑在我从卡片中提取样式数组后,解决方案可能与Javascript的ForEach()有关?我真的不知道该怎么继续下去。我的代码是: 视图。py:Javascript 使用Django为AJAX提取多个HTML DOM元素时出现问题,javascript,jquery,html,django,ajax,Javascript,Jquery,Html,Django,Ajax,我正在尝试在一个web应用程序上实现一个功能,其中我有一个比萨菜单,并且每张卡上列出的价格(功能来自Bootstrap)根据所选比萨的风格(普通/西西里)、大小(小/大)和名称(奶酪/特色)动态更新。我正在使用一个循环来创建所有的卡片,方法是在后端使用ORM查询数据库,这将获取餐馆老板添加的所有现有比萨饼,并为每个比萨饼创建一个菜单项。然后,我打算提取每个比萨饼的名称、样式和尺寸选择,并在实现用户购买比萨饼的结账功能之前,使用AJAX在卡片的价格区域中动态呈现特定类型比萨饼的价格。问题主要在于我
from django.http import HttpResponse, Http404, HttpResponseRedirect, JsonResponse
from django.contrib.auth.models import User
from django.shortcuts import render
from .models import Topping, Size, Pizza, Sub, Pasta, Platter, Salad, pizza_styles, sizes
from django.urls import reverse
# Create your views here.
def index(request): # this home page will be the menu page
return render(request, "orders/index.html")
def pizza(request): # this home page will be the menu page
styles = [x[0] for x in pizza_styles]
# these lists have to be created because pizza_styles and sizes are naturally a list of tuples
propSizes = [x[0] for x in sizes]
context = {
'pizzas': Pizza.objects.all(),
'styles': styles,
'sizes': propSizes,
}
print(propSizes, styles, Pizza.objects.first().name) # diagnostic purposes
return render(request, "orders/pizza.html", context)
#below is the function I'm currently stuck on (the front end is the tough part I think)
def get_price(request):
style = request.GET.get('style', None)
size = request.GET.get('size', None)
name = request.GET.get('name', None)
data = {
'price' = Pizza.objects.filter(name=name, style=style, size=size).price
# get the pizza style, size, and type from the front end and query database on those filters to get price
}
return JsonResponse(data)
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("pizza", views.pizza, name="pizza"),
path("get_price", views.get_price, name='get_price'),
]
{% extends "orders/index.html" %}
{% block item %}
<main class="containerX">
<div class="row">
{% for pizza in pizzas %}
<div class="card border-primary mb-3" id="card">
<div class="card-body">
<h5 class="card-title" id="name">{{ pizza.name }}</h5>
<p class="card-text">
<select id="style">
{% for style in styles %}
<option value="{{ style }}">{{ style }}</option>
{% endfor %}
</select>
</p>
<p class="card-text">
<select id="size">
{% for size in sizes %}
<option value="{{ size }}">{{ size }}</option>
{% endfor %}
</select>
</p>
<p class="card-text" id="price"> price depending on selection </p>
<a href="#" class="btn btn-primary">Add to Cart</a>
</div>
</div>
{% empty %}
<h2>No pizzas currently on offer. Sorry!</h2>
{% endfor %}
</div>
</main>
<script>
var size = document.querySelector('#size').value;
var name = document.querySelector('#name').textContent;
var style = document.querySelector('#style').value;
var price = document.querySelector('#price').value;
console.log(size, name, style, price)
// load default price set up in python too
(style.onchange || size.onchange) = function(){
// then send the ajax request
$.ajax({
url: '/get_price', // implement this url that will send back data
data: { // communication with the backend is to get the price from the database
'size': size,
'name': name,
'style': style,
},
dataType: 'json',
success: function (data) {
// simply update price here
price = data['price']
console.log(price)
}
});
};
</script>
{% endblock %}
url.py:
from django.http import HttpResponse, Http404, HttpResponseRedirect, JsonResponse
from django.contrib.auth.models import User
from django.shortcuts import render
from .models import Topping, Size, Pizza, Sub, Pasta, Platter, Salad, pizza_styles, sizes
from django.urls import reverse
# Create your views here.
def index(request): # this home page will be the menu page
return render(request, "orders/index.html")
def pizza(request): # this home page will be the menu page
styles = [x[0] for x in pizza_styles]
# these lists have to be created because pizza_styles and sizes are naturally a list of tuples
propSizes = [x[0] for x in sizes]
context = {
'pizzas': Pizza.objects.all(),
'styles': styles,
'sizes': propSizes,
}
print(propSizes, styles, Pizza.objects.first().name) # diagnostic purposes
return render(request, "orders/pizza.html", context)
#below is the function I'm currently stuck on (the front end is the tough part I think)
def get_price(request):
style = request.GET.get('style', None)
size = request.GET.get('size', None)
name = request.GET.get('name', None)
data = {
'price' = Pizza.objects.filter(name=name, style=style, size=size).price
# get the pizza style, size, and type from the front end and query database on those filters to get price
}
return JsonResponse(data)
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("pizza", views.pizza, name="pizza"),
path("get_price", views.get_price, name='get_price'),
]
{% extends "orders/index.html" %}
{% block item %}
<main class="containerX">
<div class="row">
{% for pizza in pizzas %}
<div class="card border-primary mb-3" id="card">
<div class="card-body">
<h5 class="card-title" id="name">{{ pizza.name }}</h5>
<p class="card-text">
<select id="style">
{% for style in styles %}
<option value="{{ style }}">{{ style }}</option>
{% endfor %}
</select>
</p>
<p class="card-text">
<select id="size">
{% for size in sizes %}
<option value="{{ size }}">{{ size }}</option>
{% endfor %}
</select>
</p>
<p class="card-text" id="price"> price depending on selection </p>
<a href="#" class="btn btn-primary">Add to Cart</a>
</div>
</div>
{% empty %}
<h2>No pizzas currently on offer. Sorry!</h2>
{% endfor %}
</div>
</main>
<script>
var size = document.querySelector('#size').value;
var name = document.querySelector('#name').textContent;
var style = document.querySelector('#style').value;
var price = document.querySelector('#price').value;
console.log(size, name, style, price)
// load default price set up in python too
(style.onchange || size.onchange) = function(){
// then send the ajax request
$.ajax({
url: '/get_price', // implement this url that will send back data
data: { // communication with the backend is to get the price from the database
'size': size,
'name': name,
'style': style,
},
dataType: 'json',
success: function (data) {
// simply update price here
price = data['price']
console.log(price)
}
});
};
</script>
{% endblock %}
pizza.html:
from django.http import HttpResponse, Http404, HttpResponseRedirect, JsonResponse
from django.contrib.auth.models import User
from django.shortcuts import render
from .models import Topping, Size, Pizza, Sub, Pasta, Platter, Salad, pizza_styles, sizes
from django.urls import reverse
# Create your views here.
def index(request): # this home page will be the menu page
return render(request, "orders/index.html")
def pizza(request): # this home page will be the menu page
styles = [x[0] for x in pizza_styles]
# these lists have to be created because pizza_styles and sizes are naturally a list of tuples
propSizes = [x[0] for x in sizes]
context = {
'pizzas': Pizza.objects.all(),
'styles': styles,
'sizes': propSizes,
}
print(propSizes, styles, Pizza.objects.first().name) # diagnostic purposes
return render(request, "orders/pizza.html", context)
#below is the function I'm currently stuck on (the front end is the tough part I think)
def get_price(request):
style = request.GET.get('style', None)
size = request.GET.get('size', None)
name = request.GET.get('name', None)
data = {
'price' = Pizza.objects.filter(name=name, style=style, size=size).price
# get the pizza style, size, and type from the front end and query database on those filters to get price
}
return JsonResponse(data)
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("pizza", views.pizza, name="pizza"),
path("get_price", views.get_price, name='get_price'),
]
{% extends "orders/index.html" %}
{% block item %}
<main class="containerX">
<div class="row">
{% for pizza in pizzas %}
<div class="card border-primary mb-3" id="card">
<div class="card-body">
<h5 class="card-title" id="name">{{ pizza.name }}</h5>
<p class="card-text">
<select id="style">
{% for style in styles %}
<option value="{{ style }}">{{ style }}</option>
{% endfor %}
</select>
</p>
<p class="card-text">
<select id="size">
{% for size in sizes %}
<option value="{{ size }}">{{ size }}</option>
{% endfor %}
</select>
</p>
<p class="card-text" id="price"> price depending on selection </p>
<a href="#" class="btn btn-primary">Add to Cart</a>
</div>
</div>
{% empty %}
<h2>No pizzas currently on offer. Sorry!</h2>
{% endfor %}
</div>
</main>
<script>
var size = document.querySelector('#size').value;
var name = document.querySelector('#name').textContent;
var style = document.querySelector('#style').value;
var price = document.querySelector('#price').value;
console.log(size, name, style, price)
// load default price set up in python too
(style.onchange || size.onchange) = function(){
// then send the ajax request
$.ajax({
url: '/get_price', // implement this url that will send back data
data: { // communication with the backend is to get the price from the database
'size': size,
'name': name,
'style': style,
},
dataType: 'json',
success: function (data) {
// simply update price here
price = data['price']
console.log(price)
}
});
};
</script>
{% endblock %}
{%extends“orders/index.html”%}
{%block item%}
{披萨中的披萨%}
{{pizza.name}
{%用于样式中的样式%}
{{style}}
{%endfor%}
{%表示大小,单位为%}
{{size}}
{%endfor%}
价格取决于选择
{%empty%}
目前没有比萨饼出售。很抱歉
{%endfor%}
var size=document.querySelector('#size').value;
var name=document.querySelector('#name').textContent;
var style=document.querySelector(“#style”).value;
var price=document.querySelector(“#price”).value;
日志(大小、名称、样式、价格)
//加载python中设置的默认价格
(style.onchange | | size.onchange)=函数(){
//然后发送ajax请求
$.ajax({
url:“/get_price”,//实现此url以发回数据
数据:{//与后端的通信是从数据库获取价格
“大小”:大小,
“名称”:名称,
“风格”:风格,
},
数据类型:“json”,
成功:功能(数据){
//只需在这里更新价格
价格=数据[“价格”]
控制台日志(价格)
}
});
};
{%endblock%}
我对AJAX和Django的工作原理有一个初步的了解,我认为我的视图、URL和pizza.html代码原则上都是正确的,但是有一些小的实现细节我不能完全掌握,尽管我经历了几天的挫折 看起来您试图侦听实际值上的更改事件,但需要侦听Dom节点。还要确保在JavaScript之前包含jquery作为$。ajax是一个jquery函数。尝试将JavaScript更改为以下内容:
<script>
var size = document.querySelector('#size');
var name = document.querySelector('#name').textContent;
var style = document.querySelector('#style');
var price = document.querySelector('#price').value;
console.log(size, name, style, price)
// load default price set up in python too
(style.onchange || size.onchange) = function(e){
var styleValue = e.target.value;
var sizeValue = e.target.value;
// then send the ajax request
$.ajax({
url: '/get_price', // implement this url that will send back data
data: { // communication with the backend is to get the price from the database
'size': sizeValue,
'name': name,
'style': styleValue,
},
dataType: 'json',
success: function (data) {
// simply update price here
price = data['price']
console.log(price)
}
});
};
</script>
var size=document.querySelector('#size');
var name=document.querySelector('#name').textContent;
var style=document.querySelector(“#style”);
var price=document.querySelector(“#price”).value;
日志(大小、名称、样式、价格)
//加载python中设置的默认价格
(style.onchange | | size.onchange)=函数(e){
var styleValue=e.target.value;
var sizeValue=e.target.value;
//然后发送ajax请求
$.ajax({
url:“/get_price”,//实现此url以发回数据
数据:{//与后端的通信是从数据库获取价格
“大小”:sizeValue,
“名称”:名称,
“样式”:样式值,
},
数据类型:“json”,
成功:功能(数据){
//只需在这里更新价格
价格=数据[“价格”]
控制台日志(价格)
}
});
};
如果您还有其他问题,请告诉我,我会尝试帮助。1)将有多张id为“大小”和“样式”的卡,所有这些卡都需要监听下拉列表中的更改,因此这不起作用;2)DOM节点(实际的HTML)当然会保持不变,无论选择如何,但取决于选择,“document.querySelector('#size').value”输出的值正在改变,所以我不明白您的意思是我应该获取DOM节点而不是值。在任何情况下——这段代码也不起作用——有什么想法吗?我包括了jQ;错误是:“Uncaught TypeError:console.log(…)不是函数”@the | |@TanishqKumar JavaScript事件在Dom节点上,而不是值本身,您正在查找Id,因此只能有一个元素具有该Id,我想您需要查找JavaScript事件