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

 

posted @ 2018-08-08 21:26  神秘嘉宾7m  阅读(97)  评论(0编辑  收藏  举报