6.Django与Ajax

 Ajax

AJAXAsynchronous Javascript And XML)翻译成中文就是异步JavascriptXML”。即使用Javascript语言与服务器进行异步交互,传输的数据为XML当然,传输的数据不只是XML,现在更多使用json数据)。

  • 同步交互:客户端发出一个请求后,需要等待服务器响应结束后,才能发出第二个请求;
  • 异步交互:客户端发出一个请求后,无需等待服务器响应结束,就可以发出第二个请求。

AJAX除了异步的特点外,还有一个就是:浏览器页面局部刷新;(这一特点给用户的感受是在不知不觉中完成请求和响应过程)

场景:

 

优点:

  • AJAX使用Javascript技术向服务器发送异步请求
  • AJAX无须刷新整个页面

 

jquery cdn百度   src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"></script> 

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"></script>
</head>
<body>
    <h2>this is Index!</h2>
    <button class="Ajax">Ajax</button>
    <p class="content"></p>
    <script>
        $(".Ajax").click(function(){
            //alert(123)
           //发送ajax请求
            $.ajax({
                url:"/test_ajax/" ,  //请求url,不加地址它会找默认当前脚本的ip地址和端口
                type:"get", //请求方式
                success: function (data) {  //回调函数,某个事件执行完之后再去执行的函数
                    console.log(data);

                    $(".content").html(data);

                }
            })
        })
    </script>

</body>


</html>

 执行过程:

  一点击Ajax按钮,触发click这个函数,然后发就要发生ajax,给test_ajax发路径请求,当url匹配成功后,它把请求的结果交给了data,刚刚那个hello kris就交给了data;然后再执行那个回调函数能够打印,用js处理data.

Ajax数据传递

urls

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('test_ajax/', views.test_ajax),
    path('cal/', views.cal),
]

views.py

from django.shortcuts import render, HttpResponse

# Create your views here.
def index(request):

    return render(request, "index.html")
def test_ajax(request):
    print(request.GET)
    return HttpResponse("Hello kris")

def cal(request):
    print(request.POST)
    n1=int(request.POST.get("n1"))
    n2=int(request.POST.get("n2"))
    ret = n1+n2
    return HttpResponse(ret)

index.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"></script>
 7 </head>
 8 <body>
 9     <h2>this is Index!</h2>
10     <button class="Ajax">Ajax</button>
11     <p class="content"></p>
12 
13     <hr>
14     <input type="text" id="num1">+<input type="text" id="num2">=<input type="text" id="ret"><button class="cal">计算</button>
15     <script>
16         $(".Ajax").click(function(){
17             //alert(123)
18            //发送ajax请求
19             $.ajax({
20                 url:"/test_ajax/" ,  //请求url,不加地址它会找默认当前脚本的ip地址和端口
21                 type:"get", //请求方式
22                 data:{a:1,b:2},
23                 success: function (data) {  //回调函数,某个事件执行完之后再去执行的函数
24                     console.log(data);
25 
26                     $(".content").html(data);
27                 }
28             })
29         })
30         //Ajax计算求值
31         $(".cal").click(function () {
32             $.ajax({
33                 url:"/cal/",
34                 type:"post",
35                 data:{
36                     "n1":$("#num1").val(),
37                     "n2":$("#num2").val(),
38                 },
39                 success: function (data) {
40                     console.log(data);
41                     $("#ret").val(data);
42                 }
43             })
44         })
45     </script>
46 
47 </body>
48 
49 
50 </html>

 

 基于Ajax的登录验证

  用户在表单输入用户名与密码,通过Ajax提交给服务器,服务器验证后返回响应信息,客户端通过响应信息确定是否登录成功,成功,则跳转到首页,否则,在页面上显示相应的错误信息。

models

from django.db import models

# Create your models here.
class User(models.Model):
    name = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)

views

from app01.models import User
def login(request):
    print(request.POST)
    user = request.POST.get("user")
    pwd = request.POST.get("pwd")
    user = User.objects.filter(name=user, pwd=pwd).first()
    res = {"user":None, "msg":None}
    if user:
        res["user"] = user.name
    else:
        res["msg"] = "username or password wrong!"
    import json   #想把res这个字典交给data
    return HttpResponse(json.dumps(res))

index

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"></script>
</head>
<body>
    <form>
        用户名<input type="text" id="user">
        密码<input type="password" id="pwd">
        <input type="button" value="submit" class="login_btn"><span class="error"></span>
    </form>

    <script>//登录验证
        $(".login_btn").click(function () {
            $.ajax({
                url:"/login/",
                type:"post",
                data:{
                    "user":$("#user").val(),
                    "pwd":$("#pwd").val(),
                },
                success:function(data){
                    console.log(data); //json字符串
                    console.log(typeof data);

                    var data = JSON.parse(data)  //js再给它反序列化 object{}
                    console.log(data); //反序列化类似字典的object
                    console.log(typeof data);
                    if (data.user){
                        location.href="http://www.baidu.com"
                    }
                    else {
                        $(".error").html(data.msg).css({"color":"red","margin-left":"10px"})
                    }
                }
            })
        })

    </script>

</body>


</html>

基于form表单上传文件

views

def file_put(request):
    if request.method == "POST":
        print(request.POST)  #用户上传的数据
        print(request.FILES)  #拿到这个文件
        file_obj = request.FILES.get("avatar")  #把文件下载来
        with open(file_obj.name, "wb")as f:  #上传的文件名file_obj.name
            for line in file_obj:
                f.write(line)

        return HttpResponse("ok")
    return render(request, "file_put.html")

file_put

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h3>基于form表单的文件上传</h3>
<form action="" method="post" enctype="multipart/form-data">
    用户名<input type="text" name="user">
    头像<input type="file" name="avatar">
    <input type="submit">
</form>

</body>
</html>

请求头ContentType:urlencoed

file_put

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"></script>
</head>
<body>
<h3>简单的form</h3>
<form action="" method="post" enctype="application/x-www-form-urlencoded"> {#普通的键值只能用这种#}
    用户名<input type="text" name="user">
    密码<input type="password" name="pwd">
    <input type="submit">
</form>


<h3>基于form表单的文件上传</h3>
<form action="" method="post" enctype="multipart/form-data">
    用户名<input type="text" name="user">
    头像<input type="file" name="avatar">
    <input type="submit">
</form>

<h3>基于Ajax文件上传</h3>
<form action="" method="post">
    用户名<input type="text" name="user">
    <input type="button" class="btn" value="Ajax">
</form>
<script>
    $.ajax({
        url:"",
        type:"post",
        data:{
            a:1,
            b:2
        },                 //无论是ajax还是form它们都有一个默认的请求头ContentType:urlencoed ,把我们写好的数据按照某种类型编码好之后放到请求体中,然后把整个报文部分发给服务器
        success: function (data) {
            console.log(data)
        }
    })
</script>
</body>
</html>

Ajax传递json数据

file_put

<h3>基于Ajax文件上传</h3>
<form action="" method="post">
    用户名<input type="text" name="user">
    <input type="button" class="btn" value="Ajax">
</form>
<script>
    $.ajax({
        url:"",
        type:"post",
        contentType:"application/json",
        data:JSON.stringify({
            a:1,
            b:2
        }),                 //无论是ajax还是form它们都有一个默认的请求头ContentType:urlencoed ,把我们写好的数据按照某种类型编码好之后放到请求体中,然后把整个报文部分发给服务器
        success: function (data) {
            console.log(data)
        }
    })
</script>

views

def file_put(request):
    if request.method == "POST":
        print("body",request.body)  #请求报文中的请求体
        print("post",request.POST)  #用户上传的数据; 只有在ContentType:urlencoed时,request.POST才有数据

        return HttpResponse("ok")
    return render(request, "file_put.html")
'''
请求首行
请求体
'''
'''
ContentType:urlencoed   请求头 这样的编码格式 ;multipart/form-data文件上传只能用这种
请求体(a=1&b=2&c=3)
'''

 基于Ajax文件上传

file_put

    //Ajax上传文件
    $(".btn").click(function () {
        var formdata=new FormData();
        formdata.append("user",$("#user").val());   {#不断的append键值#}
        formdata.append("avatar",$("#avatar")[0].files[0]);
        $.ajax({
            url:"",
            type:"post",
            contentType:false,
            processData:false,
            data:formdata,   //把整个formdata对象放到data里边
            success: function (data) {
                console.log(data)
            }
        })
    })

views.py

def file_put(request):
    if request.method == "POST":
        print("body",request.body)  #请求报文中的请求体
        print("post",request.POST)  #用户上传的数据; 只有在ContentType:urlencoed时,request.POST才有数据
        print(request.FILES)  #拿到这个文件
        file_obj = request.FILES.get("avatar")  #把文件下载来
        with open(file_obj.name, "wb")as f:  #上传的文件名file_obj.name
            for line in file_obj:
                f.write(line)

        return HttpResponse("ok")
    return render(request, "file_put.html")

 

猜你喜欢

转载自www.cnblogs.com/shengyang17/p/9121068.html