繁体   English   中英

如何使用 javascript 和 Ajax 更新 Django html 元素

[英]How to update a Django html element with javascript and Ajax

我正在尝试使用 javascript 更新 web 页面上的 html 元素。 当主页加载时,它工作得很好,但是当我点击新产品链接时,只有上下文字符串显示在主页上

html

<!--  product/home.html -->
{% load static %}

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">

        <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
        <title>Test context</title>
    </head>
    <body>
    <h1>Test context</h1>
        <div class="container">
            {% block content %}
                Product: <span id="product-code"></span>
                <p><a href="{% url 'new-product' %}">New Product</a><p>
            {% endblock content %}

            <script type="text/javascript" src="{% static 'js/product.js' %}"></script>
        </div>
    </body>
</html>

网址.py

# cardplay/urls.py

from django.urls import path

from .views import HomePageView, NewProduct

urlpatterns = [
    path('', HomePageView.as_view()),
    path('new-product', NewProduct.as_view(), name= 'new-product'), 
]

视图.py

# /product/views.py

import random

from django.views.generic import View
from django.shortcuts import render
from django.http import JsonResponse

class HomePageView(View):
    template = 'product/home.html'

    def get(self, request):
        context = {}
        return render(request, self.template, context)

class NewProduct(View):

    def get(self, request):
        code = random.choice(['A123','M456', 'X789'])
        context = {
            'code': code,
        }
        return JsonResponse(context)

产品.js

$(document).ready(function () {
    getNewProduct();
});

function getNewProduct() {
    $.ajax(
        {
            type: "GET",
            url: 'new-product',
            cache: false,
            success: function (context) {
                displayNewProduct(context);
            }
        }
    );
}

function displayNewProduct(context) {
    var productCode = document.getElementById('product-code');
    productCode.innerText = context.code;
}

我究竟做错了什么?

正如@Swati 指出的那样,我没有调用 function

产品.js

$(document).ready(function () {
    product_link = document.getElementById('product_link')
    product_link.onclick = function(){getNewProduct()};
    getNewProduct();
});
...

html

...
<p><button id="product_link">New Product</button></p>
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM