zoukankan      html  css  js  c++  java
  • Django—Ajax

    Ajax-get

    url

        url(r'^ajax_add/', views.ajax_add),
        url(r'^ajax_demo1/', views.ajax_demo1),
    View Code

    视图

    def ajax_demo1(request):
        return render(request, "ajax_demo1.html")
    
    
    def ajax_add(request):
        i1 = int(request.GET.get("i1"))
        i2 = int(request.GET.get("i2"))
        ret = i1 + i2
        return JsonResponse(ret, safe=False)
    View Code

    html

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="x-ua-compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>AJAX局部刷新实例</title>
    </head>
    <body>
    
    <input type="text" id="i1">+
    <input type="text" id="i2">=
    <input type="text" id="i3">
    <input type="button" value="AJAX提交" id="b1">
    
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <script>
      $("#b1").on("click", function () {
        $.ajax({
          url:"/ajax_add/",
          type:"GET",
          data:{"i1":$("#i1").val(),"i2":$("#i2").val()},
          success:function (data) {
            $("#i3").val(data);
          }
        })
      })
    </script>
    </body>
    </html>
    View Code

    Ajax-post

    html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>测试AJAX的data参数</title>
    </head>
    <body>
    
    <button id="b1">点我</button>
    
    
    <input type="text" id="i1">
    <span></span>
    
    <hr>
    <div>111</div>
    <div>222</div>
    <div>333</div>
    
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <script src="/static/setupAjax.js"></script>
    <script>
        $("#b1").click(function () {
            // 先根据name 找到那个隐藏的input标签
            var csrfToken = $("[name='csrfmiddlewaretoken']").val();
            // 给/oo/发送AJAX请求
            $.ajax({
                url: '/oo/',
                type: 'POST',
                data: {
                    "name": "alex",
                    "hobby": JSON.stringify(["抽烟", "喝酒", "吹牛逼"]),
                    // "csrfmiddlewaretoken": csrfToken
                },
                success:function (res) {
                    console.log(res);
                    // 反序列化
                    // var ret = JSON.parse(res);  如果后端使用JsonResponse 返回响应,前端JS就不需要再反序列化
                    if (res.code !== 0){
                        console.log(res.err);
                    } else {
                        console.log(res.msg);
                    }
    
                }
            })
        });
        var $i1 = $("#i1");
        // 给 i1 标签绑定一个失去焦点的事件
        $i1.on("input", function () {
            // this  --> 触发当前事件的DOM对象
            // 1. 取到用户输入的用户名
            var username = $(this).val();
            var _this = this;
            // 2. 发送到后端
            $.ajax({
                url: '/check/',
                type: 'get',
                data: {"username": username},
                success:function (res) {
                    console.log(res);
                    if (res.code !== 0){
                        // 表示用户名已经存在
                        $(_this).next().text(res.msg).css("color", "red")
                    }
                }
            })
            // 3. 根据响应的结果做操作
        });
    
        // 给 i1 标签绑定一个获取焦点的事件
        $i1.focus(function () {
            $(this).next().text("");
        })
    
    </script>
    
    </body>
    </html>
    View Code

    要引入的文件

    /*
    * 此文件一用于判断 ajax请求是不是非安全请求,如果是就在请求头中设置csrf_token
    * */
    
    // 定义一个从Cookie中根据name取值的方法
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    // 调用上面的方法,从cookie中取出csrftoken对应的值
    var csrftoken = getCookie('csrftoken');
    
    //
    function csrfSafeMethod(method) {
      // these HTTP methods do not require CSRF protection
      return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    
    $.ajaxSetup({
      beforeSend: function (xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
          xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
      }
    });
    js文件

    Ajax-post-upload

    html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>上传文件</title>
    </head>
    <body>
    
    <form action="/upload/" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="file" name="file" id="f1">
        <input type="submit" value="提交">
        <button id="b1" type="button">点我</button>
    </form>
    
    
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <script src="/static/setupAjax.js"></script>
    
    <script>
        $("#b1").click(function () {
            // 创建一个FormData对象
            var obj = new FormData();
            // 将要上传的文件数据添加到对象中
            obj.append("file", document.getElementById("f1").files[0]);
            obj.append("name", "alex");
            $.ajax({
                url: "/upload/",
                type: "post",
                processData: false,  // 不让jQuery处理我的obj
                contentType: false,  // 不让jQuery设置请求的内容类型
                data: obj,
                success:function (res) {
                    console.log(res);
                }
            })
    
        })
    </script>
    </body>
    </html>
    View Code

    视图

    # 上传文件测试
    def upload(request):
        if request.method == "POST":
            # 从请求中取上传的文件数据
            file_obj = request.FILES.get("file")
            filename = file_obj.name
    
            with open(filename, "wb") as f:
                for chunk in file_obj.chunks():
                    f.write(chunk)
        return render(request, "upload.html")
    View Code
  • 相关阅读:
    来了!GitHub for mobile 发布!iOS beta 版已来,Android 版即将发布
    五角场之殇。曾与张江、漕河泾、紫竹齐名。如今,上海四大IT科技园是否还在?
    Visual Studio Online 的 FAQ:iPad 支持、自托管环境、Web 版 VS Code、Azure 账号等
    VS Code 1.40 发布!可自行搭建 Web 版 VS Code!
    Visual Studio Online,带来四种开发模式,未来已来。
    基于七牛云对象存储,搭建一个自己专属的极简Web图床应用(手摸手的注释讲解核心部分的实现原理)
    css伪元素::before与::after使用基础示例
    gcc生成静态链接库与动态链接库步骤,并链接生成可执行文件的简单示例
    shell求水仙花数
    shell实现简单的数组排序
  • 原文地址:https://www.cnblogs.com/benson321/p/9445796.html
Copyright © 2011-2022 走看看