ajax的get請求


需求:校驗用戶名和密碼

1.導包

導入一個jquery包

2.編寫

視圖:需要兩個視圖

第一個:返回頁面

第二個:處理ajax提交的數據,請求,返回響應

 

視圖:

# 提供頁面
def ajaxdemo(request):
    return render(request,"ajaxdemo.html")

from django.http import JsonResponse
# 處理ajax請求
def ajaxreq(request):
    """
    接收用戶的請求   校驗用戶名  密碼
        參數:  username  password
    處理請求
        查詢數據庫  查看指定用戶名密碼的用戶是否存在
    返回響應
        存在或者  不存在
    :param request:
    :return:
    """
    print(request.GET)
    username = request.GET.get("username")
    password = request.GET.get("password")
    result = {"code":10000,"msg":""}
    if username and password:
        flag = User.objects.filter(name=username,password=setPassword(password)).first()
        if flag:
            result["msg"]= "存在"
        else:
            result["msg"]= "不存在"
            result["code"]=10001
    else:
        result["msg"] = "用戶名或者密碼為空"
        result["code"] = 10002
    return JsonResponse(result)

模板   ajaxdemo.html 

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

<h3>校驗用戶名密碼</h3>
<form action="">
    <input id="username" type="text" name="username" placeholder="用戶名"><br>
    <input id="password" type="password" name="password" placeholder="密碼"><br>
    <input id="checkvalue" type="button" value="校驗">

</form>
<p id="content"></p>


<script>
    $("#checkvalue").click(
        function () {
            // 獲取到填寫的數據
            var username = $("#username").val();
            var password = $("#password").val();
            // 構建請求的url
            var url = "/ajaxreq/?username=" + username + "&password=" + password;
            // 發送一個請求   ajax 請求
            $.ajax({
                url:url,  // ajax請求要請求的地址
                type:"get", // 請求的類型  get  post
                data:"", // 請求要發送的數據  常在post請求中使用,get請求只需要拼接請求的url就可以
                success:function (data) {
                    // 請求成功之后要執行的方法
                    // data  接收請求成功之后的返回值
                    console.log(data);
                    {#console.log(data["code"]);#}
                    {#console.log(data["msg"]);#}
                    $("#content").text(data["msg"]);
                },
                error:function (error) {
                    // 請求失敗之后要執行的內容
                }
            })
            //  拿到響應
        }
    )



</script>


</body>
</html>

路由:

 

path('ajaxdemo/', ajaxdemo),
path('ajaxreq/', ajaxreq),

 

 ajax發送get請求總結

1.編寫html

提供 input  --> 獲取數據

提供按鈕  --> 觸發方法  ajax請求

ajax  --> 發送請求  get 請求

    url  發送地址  get 請求,需要拼接參數到 url 中  

    data  發送數據

    type  發送的請求方式  get 

2.第一個視圖:提供頁面的支持

3.第二個視圖:處理  ajax 請求,返回響應

    響應內容: json

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM