AJAX

AJAX准备知识:JSON

什么是 JSON ?

  • JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation)
  • JSON 是轻量级的文本数据交换格式
  • JSON 独立于语言 *
  • JSON 具有自我描述性,更易理解

* JSON 使用 JavaScript 语法来描述数据对象,但是 JSON 仍然独立于语言和平台。JSON 解析器和 JSON 库支持许多不同的编程语言

正确的json对象:

["one", "two", "three"]
{ "one": 1, "two": 2, "three": 3 }
{"names": ["张三", "李四"] }
[ { "name": "张三"}, {"name": "李四"} ] 

 不正确的json对象:

复制代码
{ name: "张三", 'age': 32 }         // 属性名必须使用双引号
[32, 64, 128, 0xFFF]             // 不能使用十六进制值
{ "name": "张三", "age": undefined }    // 不能使用undefined
{ "name": "张三",
  "birthday": new Date('Fri, 26 Aug 2011 07:13:10 GMT'),
  "getName":  function() {return this.name;}  // 不能使用函数和日期对象
}
复制代码

stringify与parse方法

JavaScript中关于JSON对象和字符串转换的两个方法:

JSON.parse(): 用于将一个 JSON 字符串转换为 JavaScript 对象 

JSON.parse('{"name":"wl"}');
JSON.parse('{name:"wl"}') ;      // 错误
JSON.parse('[18,undefined]') ;     // 错误

JSON.stringify(): 用于将 JavaScript 值转换为 JSON 字符串。 

JSON.stringify({"name":"wl"})

AJAX简介

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

AJAX 不是新的编程语言,而是一种使用现有标准的新方法。

AJAX 最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。(这一特点给用户的感受是在不知不觉中完成请求和响应过程)

AJAX 不需要任何浏览器插件,但需要用户允许JavaScript在浏览器上执行。

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

示例

页面输入两个整数,通过AJAX传输到后端计算出结果并返回

views.py代码

from django.shortcuts import render, HttpResponse

def index(request):
    if request.method == 'POST':
        i1 = request.POST.get('i1')
        i2 = request.POST.get('i2')
        i3 = int(i1) + int(i2)
        return render(request, 'index.html', {'i1': i1, 'i2': i2, 'i3': i3})
    return render(request, 'index.html')


def calc(request):
    i1 = request.POST.get('i1')
    i2 = request.POST.get('i2')
    i3 = int(i1) + int(i2)
    return HttpResponse(i3)

HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
<input type="text" name="i1">+
<input type="text" name="i2">=
<input type="text" name="i3">
<button id="b1">计算</button>

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    $('#b1').click(function () {
        $.ajax({
            url:'/calc/',
            type:'post',
            data:{
                i1:$('[name="i1"]').val(),
                i2:$('[name="i2"]').val(),
            },
            success:function (res) {
                 $('[name = "i3"]').val(res)
            }
        })

    })
</script>
</body>
</html>

urls.py

from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
    url(r'^calc/', views.calc),
]

参数

$.ajax({
    url: '/ajax_test/',   #  提交的地址
    type: 'post',          # 提交的方式
    data: {                  #  数据
        name: 'alex',
        age: 73,
        hobby: JSON.stringify(['大保健', 'cnb', '画大饼'])  #提交多个数据
    },
    success: function (res) {    # 回调函数
        $('[name="ii3"]').val(res)
    },
    error: function (res) {       #错误
                console.log(res)
    }
})


#views
import json
def ajax_test(request):
    print(request.POST)
    # hobby = request.POST.getlist('hobby[]')
    hobby = request.POST.get('hobby')
    hobby = json.loads(hobby)
    print(hobby, type(hobby))
    # int('a')
    return HttpResponse('OK')

AJAX上传文件

urls.py

from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
    url(r'^calc/', views.calc),
    url(r'^upload/', views.upload),
]

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="file" id="f1">
<button id="b1">上传</button>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    $('#b1').click(function () {
        var form_obj = new FormData(); #组建FormData对象
        form_obj.append('x1',$('#f1')[0].files[0])

        $.ajax({
            url:'/upload/',
            type : 'post',
            data: form_obj,
            processData:false, # 不处理编码方式
            contentType:false,  #不处理contentType请求头
            success:function (res) {
                alert('ok')
                
            }
        })
    })

</script>

</body>

views.py

def upload(requset):
    if requset.is_ajax():
        file_obj = requset.FILES.get('x1')
        with open(file_obj.name,'wb') as f:
            for i in file_obj.chunks():
                f.write(i)
    return render(requset,'upload.html')

AJAX通过CSRF校验

一.模板中使用csrf_token 标签

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
<input type="text" name="i1">+
<input type="text" name="i2">=
<input type="text" name="i3">
<button id="b1">计算</button>

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
{% csrf_token %}
<script>
    $('#b1').click(function () {
        $.ajax({
            url:'/calc/',
            type:'post',
            data:{
                csrfmiddlewaretoken:  $('[name="csrfmiddlewaretoken"]').val(),
                i1:$('[name="i1"]').val(),
                i2:$('[name="i2"]').val(),

            },
            success:function (res) {
                 $('[name = "i3"]').val(res)
            }
        })

    })
</script>
</body>
</html>

二.获取请求头

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
<input type="text" name="i1">+
<input type="text" name="i2">=
<input type="text" name="i3">
<button id="b1">计算</button>

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
{% csrf_token %}
<script>
    $('#b1').click(function () {
        $.ajax({
            url:'/calc/',
            type:'post',
               headers:{
           'X-csrftoken': $('[name="csrfmiddlewaretoken"]').val(),
        },
            data:{

                i1:$('[name="i1"]').val(),
                i2:$('[name="i2"]').val(),

            },
            success:function (res) {
                 $('[name = "i3"]').val(res)
            }
        })

    })
</script>
</body>
</html>

三.文件(常用)

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;
}

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);
        }
    }
});

 settings.py 静态文件配置

STATICFILES_DIRS = [
    os.path.join(BASE_DIR,'static')
]

模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
<input type="text" name="i1">+
<input type="text" name="i2">=
<input type="text" name="i3">
<button id="b1">计算</button>

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script src="/static/js/ajax_setup.js"></script>

<script>
    $('#b1').click(function () {
        $.ajax({
            url:'/calc/',
            type:'post',
            data:{

                i1:$('[name="i1"]').val(),
                i2:$('[name="i2"]').val(),

            },
            success:function (res) {
                 $('[name = "i3"]').val(res)
            }
        })

    })
</script>
</body>
</html>

 

posted @ 2019-02-15 00:13  答&案  阅读(136)  评论(0编辑  收藏  举报