天天看点

ajax post提交数据_django 的ajax提交与表单提交记录

好记性不如烂笔头;

据说的ajax提交比表单提交要好,可以不用重新刷新页面;

表单提交:MTV模式

# 局部禁用csrf保护
           

显示:

<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/hello/csrf/" method="post">
{#    {% csrf_token %}#}
    用户名:<input type="text" name="username"> <br>
    <input type="submit">
</form>
</body>
</html>
           

运行python manage.py runserver,输入地址:

ajax post提交数据_django 的ajax提交与表单提交记录

ajax提交,参照教程;

def handle_ajax(request):
    print(1111)
    if request.is_ajax():
        return JsonResponse({"code":0,'msg':"登录成功"})
    print(2222)
    return render(request,"ajax1.html")
           
<form method="POST" action="">
    {% csrf_token %}
    <input id="username" type="text" name="username" />
{#    <input type="submit" value="提交"/>#}
    <a onclick="submitForm();">Ajax提交</a>
</form>
<script src="https://cdn.bootcss.com/jquery/1.12.1/jquery.min.js"></script>
<script>
    function submitForm(){
        var csrf = $('input[name="csrfmiddlewaretoken"]').val();
        console.log(csrf)
        var user = $('#user').val();
        $.ajax({
            url: '/hello/ajax/',
            type: 'POST',
            data: { "user":user,'csrfmiddlewaretoken': csrf},
            success:function(arg){
                console.log(arg);
            }
        })
    }

</script>
           

运行:无跳动提交

ajax post提交数据_django 的ajax提交与表单提交记录
ajax post提交数据_django 的ajax提交与表单提交记录

简便的 ajax提交

<
           

继续阅读