美文网首页
django:jquery中ajax的简单使用,另一个观点

django:jquery中ajax的简单使用,另一个观点

作者: dddddo | 来源:发表于2019-11-16 06:59 被阅读0次

    对于文章django:jquery中ajax的简单使用,可以用一种方式分析。
    创建django项目projectaa,创建应用appaa。
    在urls窗口编写代码,projectaa/projectaa/urls:

    from django.contrib import admin
    from django.urls import path
    from appaa import views
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('bb/', views.bb),
        path('cal/', views.cal),
    ]
    

    在views窗口编写代码,projectaa/appaa/views:

    from django.shortcuts import HttpResponse, render
    @csrf_exempt
    def bb(request):
        return render(request, 'bbbb.html')
    @csrf_exempt
    def cal(request):
        aa = request.POST.get('input_a')
        bb = request.POST.get('input_b')
        cc = int(aa) + int(bb)
        return HttpResponse(cc)
    

    在template创建bbbb.html,并编写代码,projectaa/template/bbbb.html:

    <!DOCTYPE html>
    {% load staticfiles %}
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form action="." method="post">
            {% csrf_token %}
            <input type="text" id="input_a">
            <input type="text" id="input_b">
            <p>The sum of a and b is </p>
            <input type="text" id="input_c">
            <input type="button" onclick="calculate()" value="Calculate">
        </form>
        <script src="{% static 'jquery-3.4.1.js' %}"></script>
        <script>
            function calculate(){
                $.ajax({
                    url: "/cal/",
                    type: "post",
                    data: {
                        "input_a":$('#input_a').val(),
                        "input_b":$('#input_b').val(),
                        },
                    success:function (data) {
                        console.log(data);
                        $("#input_c").val(data);
                        }
                })
            }
        </script>
    </body>
    </html>
    

    创建static文件夹。因为要使用jquery,所以要下载jquery的较新的版本,并放置在static文件夹中,此文中路径是,
    projectaa/static/jquery-3.4.1.js。
    在setting中设置static文件夹路径,在setting文件最下面增加以下代码,

    STATIC_URL = '/static/'
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'static'),
    )
    

    在template/aaaa.html中增加以下代码,

    {% load staticfiles %}
    

    在浏览器中输入地址127.0.0.1:8000/bb/。
    如果没有实现目的,尝试在terminal中运行命令
    python manage.py makemigrations
    python manage.py migrate
    python manage.py runserver

    相关文章

      网友评论

          本文标题:django:jquery中ajax的简单使用,另一个观点

          本文链接:https://www.haomeiwen.com/subject/enbeictx.html