<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>带参数的Ajax</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="/static/js/jquery.js"></script>
    <script src="/static/js/jquery.cookie.js"></script>
    <script>
        $(function () {
            $('.btn').click(function () {
                var num1 = $('#num1').val();
                var num2 = $('#num2').val();
                $.ajax({
                    url: '/upload/u_21/',
                    type: 'post',
                    contentType: "json",
                    headers: {
                        'X-CSRFTOKEN': $.cookie('csrftoken')
                    },
                    data: JSON.stringify({
                        num1: num1,
                        num2: num2
                    }),
                    success: function (response) {
                        $('#sum').attr('placeholder', response)
                    }
                })


            })
        })
    </script>
</head>
<body>
<div class="container">
    <div class="page-header">
        <h1>带参数的Ajax
            <small>Subtext for header</small>
        </h1>
    </div>

    <form>
        {% csrf_token %}
        <label for="num1"></label>
        <input type="text" id="num1" placeholder="请输第一个数字">
        +
        <label for="num2"></label>
        <input type="text" id="num2" placeholder="请输第一个数字">
        =
        <label for="sum"></label>
        <input type="text" id="sum" placeholder="不需要填写,系统生成">
        <input type="button" class="btn btn-success btn-sm" value="点击求和">
    </form>


</div>


</body>
</html>

VIEW.py文件

from django.shortcuts import render,HttpResponse
import json
# Create your views here.

def u_2(request):
    return render(request,'u_2.html')
def u_21(request):
    # 返回一个字节对象
    obj = request.body
    # 解码 b'{"num1":"1","num2":"2"}'
    obj_json = obj.decode('utf8')
    # json反序列化
    obj_dict = json.loads(obj_json)
    num1 = obj_dict['num1']
    num2 = obj_dict['num2']
    print(json.dumps(num1+num2))
    return HttpResponse(json.dumps(int(num1)+int(num2)))

URLS.py文件

from django.urls import path, re_path, include
from upload import views

urlpatterns = [
    re_path('^u_2$', views.u_2, name='u_2'),
    re_path('^u_21/$', views.u_21, name='u_21'),
]