前端之promise


Promise是一個非常重要的方法,它可以是一些異步操作最后歸為有序的進行。

 

url:

from django.contrib import admin
from django.urls import path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path("index/",views.index),
    path("index2/",views.index2)

]

 

views:

from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse
# Create your views here.

def index(request):
    if request.method == "POST":
        return redirect("/index2/")
    return render(request,"index.html")

def index2(request):
    res = {"code":1}
    return JsonResponse(res)

 

index:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <button id="b1">點擊</button>
</body>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    function sendmsg(path){
        return new Promise(function(resolve,reject){
            $.ajax({
                url:path,
                type:"get",
                success:function(data){
                    {#console.log(111)#}
                    console.log(data)
                    resolve(data)
                },
                error:function(err){
                    reject(err)
                }
            })
        })
    };
    $("#b1").click(function(){
        var ret = sendmsg("/index2/");
        ret.then(function (data) {
            alert(data)
        }).catch(function (err) {
            alert(err)
        })
    })
</script>
</html>

 


免責聲明!

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



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