django:一个简单的Ajax无刷计算器

导读:本篇文章讲解 django:一个简单的Ajax无刷计算器,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

这只是一个基础功能模板,更重要的意义在于基于其原理的扩展应用上。

一,路由

MyDjango/urls.py:
from django.urls import path, include
from django.contrib import admin

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include(('user.urls', 'user'), namespace='user')),
]

user/urls.py:
from django.urls import path
from user.views import *

urlpatterns = [
    path('basicexample', basicexample, name='basicexample'),
    path('add', add, name='add'),
]

二,视图

user/views.py:
from django.shortcuts import render
from django.http import HttpResponse

def basicexample(request):
    print(request.GET)
    return render(request, 'test.html')

def add(request):
    a = int(request.GET['a'])
    b = int(request.GET['b'])
    res = str(a + b)
    print('res:', res)
    return HttpResponse(res)

三,模板

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax无刷计算器</title>
</head>
<body>
<p>输入两个整数</p>
<form action="add" method="get">
    {% csrf_token %}
    a: <input type="text" id="a" name="a"><br>
    b: <input type="text" id="b" name="b"><br>
    <p>result: <span id="res"></span></p>
    <button type="button" id="sum">求和</button>
</form>
<script src="{% static 'js/jquery-1.11.0.js' %}"></script>
<script>
    $(document).ready(function () {
        $('#sum').click(function () {
            var a = $('#a').val();
            var b = $('#b').val();
            $.ajax({
                url: 'add',
                type: 'GET',
                data: {'a': a, 'b': b},
                success: function (res) {
                    alert("上传成功")
                    $('#res').html(res)
                },
                error: function () {
                    alert("上传失败!")
                    console.log(data)
                }
            })
        });
    });
</script>
</body>
</html>

在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/98139.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!