Django学习笔记-Ajax

版权声明:欢迎转载,转载需要明确表明转自本文 https://blog.csdn.net/u012442157/article/details/79666333

Ajax实现页面无刷新

具体问题:
在前端有些数据要提交,但是没有form表单,所以要构建一个form表单,然后在提交。

一、HTML界面

<!DOCTYPE html>
<html>
<body>
<p>请输入两个数字</p>
<form action="/add" method="get">
    a: <input type="text" id="a" name="a"> <br>
    b: <input type="text" id="b" name="b"> <br>
    <p>result: <span id='result'>{{ result }}</span></p>
    <button type="button" id='sum'>提交</button>
</form>

<script src="static/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $("#sum").click(function(){
            var a = $("#a").val();
            var b = $("#b").val();
            test = {'a': a, 'b': b};

            $.ajax({
                type: "get",
                url: "/add",
                data: test,
                dataType : "json",
                success: function(respMsg){
                    alert(respMsg)
                    $('#result').html(respMsg)
                }
            });
        });
    });
</script>
</body>
</html>

二、views代码

def add(request):
    a = int(request.GET['a'])
    b = int(request.GET['b'])

    json_data = {'result': a+b}
    return JsonResponse(json.dumps(json_data), safe=False)

三、urls.py

四、具体问题是需要上传一个文件

HTML界面

猜你喜欢

转载自blog.csdn.net/u012442157/article/details/79666333