前端之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>
原文地址:https://www.cnblogs.com/stfei/p/9396713.html