• Django 学习笔记(五) --- Ajax 传输数据


    人生苦短 ~ 

    Tips:仅适用于 Python 3+(反正差别不大,py2 改改也能用)。因为据 Python 之父 Guido van Rossum 说会在 2020 年停止对 Python 2 的官方支持,所以如果你还在使用 Python 2 那就要早做准备了,毕竟没有官方的支持使用起来也不顺心的。

    1. Ajax 介绍

    Ajax 即 “Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。
    Ajax = 异步 Javascript 和 XML(标准通用语言的子集)。
    Ajax 是一种用于创建快速动态网页的技术。
    Ajax 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
    通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
    传统的网页(不使用 Ajax)如果需要更新内容,必须重载整个网页页面。
     
    来源:百度百科

    2. 视图页面

     在文件夹  emplates 中新建页面 ajax_request.html 和在 /static/js/ajax_request.js 页面,html 文件暂时添加如下代码,js 文件暂时为空:

    <!DOCTYPE html>
    {% load static %} <!-- 模板标签加载静态文件路径,也可以改成 load staticfiles -->
    <html>
    <head>
        <title>HelloDjango</title>
        <script type="text/javascript" src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script><!-- 这里引入的是百度的 JQuery -->
        <script type="text/javascript" src="{% static 'js/ajax_request.js' %}"></script> <!-- 我们 get post 请求需要使用的自定义 js -->
    </head>
    <body>
        
    </body>
    </html>

    在我们的应用模块中 /mydjango/views.py 添加以下四个函数,函数暂时返回空:

    # 默认访问页面
    def ajax_index(request):
        return render(request, 'ajax_request.html')
        
    # Ajax GET 提交数据
    def ajax_get(request):
        return HttpResponse('')
        
    # Ajax POST 提交数据
    def ajax_post(request):
        return HttpResponse('')
        
    # Ajax 返回 JSON 数据
    def ajax_json(request):
        return HttpResponse('')

    在我们的应用模块中 /mydjango/urls.py 添加一下四个访问链接:

    path('ajax/index/', views.ajax_index),
    path('ajax/get/', views.ajax_get),
    path('ajax/post/', views.ajax_post),
    path('ajax/json/', views.ajax_json),

    3. GET 提交数据

    在 ajax_request.html 页面 body 中添加需要提交数据的 html 代码:

        <h3>GET 提交数据:</h3>
        <input type="number" id="num1" />&nbsp;*&nbsp;
        <input type="number" id="num2" />
        <button onclick="fun_get();">&nbsp;=&nbsp;</button>
        <font style="color:red;"><span id="result_get"></span></font>
        <hr />

    在 views.py 中的 ajax_get 方法中获取数据并实现操作:

    # Ajax GET 提交数据
    def ajax_get(request):
        a = request.GET.get("a")
        b = request.GET.get("b")
        n = int(a) * int(b)
        return HttpResponse(str(n))

    js 添加 get 请求操作:

    function fun_get() {
        var a = $("#num1").val();
        var b = $("#num2").val();
        $.get("/mydjango/ajax/get/", { 'a': a, 'b': b }, function(ret){
            $('#result_get').html(ret);
        });
    }

    可以看到浏览器请求的地址和执行结果:

    4. POST 提交数据

    在 ajax_request.html 页面 body 中添加需要提交数据的 html 代码:

        <h3>POST 提交数据:</h3>
        <input type="number" id="num_post1" />&nbsp;*&nbsp;
        <input type="number" id="num_post2" />
        <button onclick="fun_post();">&nbsp;=&nbsp;</button>
        <font style="color:red;"><span id="result_post"></span></font>
        <hr />

    在 views.py 中的 ajax_post 方法中获取数据并实现操作:

    # Ajax POST 提交数据,csrf_exempt 是告诉你的视图不要检查 csrf 标记,不加的话会报 403 错误
    # 需要导入包 from django.views.decorators.csrf import csrf_exempt
    @csrf_exempt
    def ajax_post(request):
        a = request.POST.get("a", 0) # 0 是默认值
        b = request.POST.get("b", 0)
        n = int(a) * int(b)
        return HttpResponse(str(n))

    js 添加 post 请求操作:

    function fun_post() {
        var a = $("#num_post1").val();
        var b = $("#num_post2").val();
        $.ajax({
            type : 'post',
            url : '/mydjango/ajax/post/',
            dataType : 'json',
            data : {
                'a': a,
                'b': b
            },
            success : function(ret) {
                $('#result_post').html(ret);
            },
            error : function(err) {
            }
        });
    }

    可以看到浏览器请求的地址和执行结果:

    5. POST 返回 JSON 数据

    在 ajax_request.html 页面 body 中添加需要提交数据的 html 代码:

        <h3>POST 请求 JSON 数据:</h3>
        <button onclick="fun_json();">&nbsp;请求 JSON&nbsp;</button>
        <font style="color:green;"><span id="result_json"></span></font>
        <hr />

    在 views.py 中的 ajax_json 方法中获取数据并实现操作:

    # Ajax 返回 JSON 数据,csrf_exempt 是告诉你的视图不要检查 csrf 标记,不加的话会报 403 错误
    # 需要导入包 from django.views.decorators.csrf import csrf_exempt
    @csrf_exempt
    def ajax_json(request):
        name_dict = {'name': 'Django', 'age': 18, 'phone': '13500000000'}
        return HttpResponse(json.dumps(name_dict), content_type='application/json')

    js 添加 post 请求 JSON 操作:

    function fun_json() {
        $.ajax({
            type : 'post',
            url : '/mydjango/ajax/json/',
            dataType : 'json',
            success : function(ret) {
                $('#result_json').html(JSON.stringify(ret));
            },
            error : function(err) {
            }
        });
    }

    可以看到浏览器请求的地址和执行结果:

    ~ 我学 Python

  • 相关阅读:
    spring定时器的cronexpression表达式
    Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
    ORA-12505, TNS:listener does not currently know of SID given in connect desc
    The Network Adapter could not establish the connection
    Shell中的>/dev/null 2>&1 与 2>&1 >/dev/null 与&>/dev/null 的区别
    大道至简、大智若愚—GO语言最佳详解实践
    rsync使用详解
    一次TIME_WAIT和CLOSE_WAIT故障和解决办法
    Go的CSP并发模型实现:M, P, G
    如何优雅打印nginx header和body
  • 原文地址:https://www.cnblogs.com/yjq520/p/9024767.html
Copyright © 2020-2023  润新知