Ajax传参配合Django范例

直接上代码分析

使用的时候和平常没有什么差别
主要注意传POST请求时,Django中的csr限制
只需要在页面中传入csrfmiddlewaretoken的值,ajax提取传到后端即可

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/js/jquery-3.3.js"></script>
</head>
<body>

<h4>indexx</h4>


<button class="btn">提交Ajax</button>
<p class="show"></p>
<hr>
{% csrf_token %}

<input type="text" id="num1"> + <input type="text" id="num2"> = <input type="text" id="ret"> <button class="cal">计算</button>



<script>
    //  简单的ajax请求
    $(".btn").click(function () {
        $.ajax({
            url:"/handle_ajax/",
            type:"get",
            success:function (response) {
                console.log(response);
                $(".show").html(response)
            }
        })
        
    })
    //  get方式传参
    $(".cal").click(function () {
        var num1=$("#num1").val();
        var num2=$("#num2").val();

        $.ajax({
            url:"/cal/",
            type:"get",
            data:{
                num1:num1,
                num2:num2
            },
            success:function (response) {
                console.log(response);
                $("#ret").val(response)
            }
        })
    })
    //  post方式传参
    $(".cal").click(function () {
        var num1=$("#num1").val();
        var num2=$("#num2").val();
        $.ajax({
            url:"/cal2/",
            type:"post",
            data:{
                num1:num1,
                num2:num2,
                csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val()
            },
            success:function (response) {
                console.log(response),
                $("#ret").val(response)
            }
        })

    })

</script>

</body>
</html>

对应的视图函数写好即可

def cla(request):

    num1 = request.GET.get("num1")
    num2 = request.GET.get("num2")
    ret = int(num1) + int(num2)

    return HttpResponse(str(ret))

你可能感兴趣的:(django,web)