1. 程式人生 > >django的ajax提交示例

django的ajax提交示例

submit color pat ces play ext ace isp 路由

兩條路由:

path(ajax_submit/, views.ajax_submit),
path(add/, views.add),

在模版文件夾裏寫出html,add.html

def add(request):
    return render(request, add.html)
    
def ajax_submit(request):
    print(request.method)
    u = request.GET.get(username, None)
    p = request.GET.get(password, None)
    if
u and u == Eric and p and p == 123: return HttpResponse(OK) else: return HttpResponse(用戶名或密碼錯誤)

jquery實現ajax提交:

技術分享圖片
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<div> <form action=""> <input id="username" type="text" placeholder="用戶名" name="username"> <input id="password" type="text" placeholder="密碼" name="password"> <input type="button" value="ajax提交"> </form> </
div> <script src="/static/jquery-1.12.4.js"></script> <script> $(function(){ $(:button).click(function(){ $.ajax({ url: /app01/ajax_submit/, type: GET, data: { username:$(#username).val(), password:$(#password).val(), }, success: function(data){ if(data==OK){ alert(驗證成功); }else{ alert(data) } } }) }) }) </script> </body> </html>
View Code

如果用戶名和密碼是Eric 和 123就顯示驗證成功,否則返回錯誤信息。

jquery的ajax的方式有$.ajax $.get $.post $.getJson都是ajax請求方式,本質上都是$.ajax

$.get(url="", data={})

django的ajax提交示例