day07 Django: Ajax介绍 简单使用 传参 jQuery: each循环

day07 Django: Ajax介绍 简单使用 传参 jQuery: each循环
 
一.Django: Ajax
 
1.目前浏览器向服务器发送请求的四种形式
    一.浏览器的地址栏直接输入url
    二.form表单里的action, 可以是GET,POST
    三.a标签, 是最常用的方式
    四.Ajax
 
2.Ajax是什么?
    asynchronous javascript and xml: 异步javascript和xml, 即使用javascript语言与服务器进行异步交互,传输的数据为xml(不止xml,现在更多使用json)
        同步交互: 排队    (客户端发一个请求后, 等服务器响应后, 才发第二个请求)
        异步交互: 不等待  (客户端发一个请求后, 无需等待服务器响应结束, 就可以发出第二个请求)
    和其他三种形式一样, 都是浏览器给服务器发送请求的技术
    和其他三种形式不一样, 页面没有刷新(整体无刷新,走的是页面的局部刷新), 没有产生新的页面
 
3.Ajax的特点
    异步
    局部刷新
 
4.引入jquery文件
    项目s15ajax > 新建static > 新建js > jquery文件
        settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
        index.html
<script src="/static/js/jquery.js"></script>
 
5.Ajax的简单使用
    点"提交Ajax"按钮发生了什么?
    1.触发了按钮的点击事件
    2.驱动程序里面的$.ajax执行, 向url:url的地址服务器发送请求
    3.服务器接收$.ajax的请求, 并返回给ajax数据
    4.$.ajax通过success的response接收到数据, 并打印到控制台
    5.$.ajax操作的是DOM, 所以页面没有刷新
    urls.py
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('handle_ajax/', views.handle_ajax),
]
    views.py
from django.shortcuts import render, HttpResponse
# Create your views here.
def index(request):
    return render(request, 'index.html', locals())
def handle_ajax(request):
    return HttpResponse('ok')
    index.html
  <body>
      <h1>你好,世界!</h1>
      <button class="btn">提交ajax</button>
      <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
      <script>
        $('.btn').click(function () {
            $.ajax({
                url: `/handle_ajax/`,
                type: 'get',
                success: function (response) {
                    console.log(response)
                }
            })
        })
      </script>
  </body>
 
6.ajax传参数
    6.1.type: "get"请求时, 传参使用: data: {}; 参数会偷摸通过url带?的形式发给服务器
        views.py
from django.shortcuts import render, HttpResponse
def index(request):
    return render(request, 'index.html', locals())
def handle_ajax(request):
    num1 = request.GET.get('num1')
    num2 = request.GET.get('num2')
    rst = int(num1) + int(num2)
    return HttpResponse(str(rst))
        index.html
<body>
    <input id="num1" type="text"> + <input id="num2" type="text"> = <input id="num3" type="text"><button class="cal">计算</button>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
      <script>
        $('.cal').click(function () {
            num1 = $('#num1').val();
            num2 = $('#num2').val();
            $.ajax({
                url: `/handle_ajax/`,
                type: 'get',
                data: {
                    num1:num1,
                    num2:num2,
                },
                success: function (response) {
                    $('#num3').val(response);
                }
            })
        })
    </script>
  </body>
    6.2.type: "post"请求时: 
        6.2.1.和type: "get"不同的是:
    由于post时: django中间件的token验证的存在: 需要把伪造的token键值对提交时一并传递过去
        6.2.2.和form表单不同的是:
    不同点一. form需要input里面必须要有name, 去和.val()组成键值对, 才能作为有效键值对传给服务器
        $.ajax不需要name, 因为我们是在data:{}里面自己组键值对
    不同点二. form里的伪造token只要{% csrf_token %}写到form表单里面, 提交时,自动会带上它
        $.ajax的{% csrf_token %}里面的键值对需要我们自己搞到data:{csrfmiddlewaretoken: $('[name="csrfmiddlewaretoken"]').val(),}里面
        6.2.3.{% csrf_token %}是什么?
    <input type="hidden" name="csrfmiddlewaretoken" value="{{ 随机的,而且只能去服务器验证一次的字符串 }}"
        views.py
from django.shortcuts import render, HttpResponse
# Create your views here.
def index(request):
    return render(request, 'index.html', locals())
def handle_ajax(request):
    num1 = request.POST.get('num1')
    num2 = request.POST.get('num2')
    rst = int(num1) + int(num2)
    return HttpResponse(str(rst))
        index.html
<body>
    <input id="num1" type="text"> + <input id="num2" type="text"> = <input id="num3" type="text"><button class="cal">计算</button>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
    {% csrf_token %}
      <script>
        $('.cal').click(function () {
            num1 = $('#num1').val();
            num2 = $('#num2').val();
            $.ajax({
                url: `/handle_ajax/`,
                type: 'post',
                data: {
                    num1:num1,
                    num2:num2,
                    csrfmiddlewaretoken: $('[name="csrfmiddlewaretoken"]').val(),
                },
                success: function (response) {
                    $('#num3').val(response);
                }
            })
        })
    </script>
  </body>
 
7.ajax的登录验证
    7.1.json数据结构的使用
    json的定义: 轻量级的数据交换格式: (javascript object notation: js对象标记)
    json特点: 本质是字符串, 而且json里面的引号都是"双引号"
    json和python数据类型的对应关系:
        js对象:       -   
        json对象:     -    number    -    string    -    true,false    -    array    -    object    -    null
        python对象:   -  int,float   -    str       -    True,False    - list,tuple  -    dict      -    None
    js里对json的序列和反序列化
        JSON.stringify()
        JSON.parse()
    7.2.django默认数据库: sqlite3 最简单的数据库, 接近于文件
        敲出你的两条命令: python manage.py makemigrations; python manage.py migrate
        项目s15ajax > db.sqlite3 >
    7.3.登录验证的流程
    1.js的ajax把需要验证的用户名密码发给服务器
    2.服务器去数据库做验证
    3.服务器把验证的结果告诉js的ajax
    4.js的ajax拿到结果, 决定如何处理
        验证成功: 使用js的location.href跳转到首页
        验证失败: 使用DOM操作把失败信息显示在网页上
        urls.py
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('login/', views.login),
]
        views.py
from django.shortcuts import render, HttpResponse
# Create your views here.
from app01.models import UserInfo
import json
def index(request):
    return render(request, 'index.html', locals())
def login(request):
    if request.method == "POST":
        rsp = {'user': '', 'error': ''}
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")
        user_obj = UserInfo.objects.filter(user=user, pwd=pwd).first()
        if user_obj:
            rsp['user'] = user
        else:
            rsp['error'] = '用户名或密码错误'
        return HttpResponse(json.dumps(rsp))
    else:
        return render(request, 'login.html', locals())
        login.html
  <body>
    {% csrf_token %}
     <div>
        用户名 <input type="text" id="user">
        密码 <input type="text" id="pwd">
         <button class="login">登录</button>
         <span class="error"></span>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
      <script>
        $('.login').click(function () {
            user = $('#user').val();
            pwd = $('#pwd').val();
            $.ajax({
                url: `/login/`,
                type: 'post',
                data: {
                    user:user,
                    pwd:pwd,
                    csrfmiddlewaretoken: $('[name="csrfmiddlewaretoken"]').val(),
                },
                success: function (response) {
                    var rsp = JSON.parse(response);
                    if (rsp.user) {
                        location.href = "/index/"
                    }else {
                        $('.error').html(rsp.error).css('color','red');
                        setTimeout(function () {
                            $(".error").html("")
                        }, 1000)
                    }
                }
            })
        })
    </script>
  </body>
 
二.jQuery: each循环
    1.数据循环: 循环列表是index, item
    var arr = [12,334,33,44,555,999]
    $.each(arr, function (index, item) {
        console.log(index, item)
    });
    2.数据循环: 循环对象是key, value
    var obj = {'name':'bajie', 'age': 123}
    $.each(obj, function (key,value) {
        console.log(key,value)
    })
    3.循环标签    
<body>
    <ul>
        <li>123asse</li>
        <li>124ggds</li>
        <li>333sdf</li>
    </ul>
     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
    <script>
        $('ul li').each(function () {
            console.log($(this).html())
        })
    </script>
</body>
 
 
 
 
 
 
 
 
 
 
 

猜你喜欢

转载自www.cnblogs.com/aiaii/p/12363096.html