Ajax

2.ajax演示

{# html #}
<button class="Ajax">Ajax</button>

// @@@@@{# js #}@@@@
$(".Ajax").click(function () {
    // 发送Ajax请求
    $.ajax({
        url:"/test_ajax/", //请求URL
        type:"get", // 请求的方式
        success:function (data) {  // 回调函数
            console.log(data)
        }
    });


});

"""python app01/views.py"""
def index(request):
    return render(request,"index.html")

3.ajax数据传递

{# html #}
<input type="text" id="input-1"> + <input type="text" id="input-2"> = <input type="text" id="res">
<button class="Ajax-data">计算</button>

// @@@@@{# js #}@@@@
$(".Ajax-data").click(function () {
    // 发送Ajax请求和数据
    $.ajax({
        url:"/test_ajax/", //请求URL
        type:"post", // 请求的方式(注意forbiden报错,解决方案后面讲)
        data:{
            a:$("#input-1").val(),
            b:$("#input-2").val(),
        }, // 发送给服务器的数据
        success:function (data) {  // 执行成功之后的回调函数,得到服务器的数据
            $("#res").val(data) // 将返回值填入对应的dom中
        }
    });
});

"""python app01/views.py"""
def test_ajax(request):
    if request.method == "GET":
        return HttpResponse("Ajax return data")
    else:
        data = request.POST
        return HttpResponse(int(data.get('a')) + int(data.get('b')))

4.基于ajax的登录验证

{# html #}
<form action="">
    用户名:<input type="text" id="user">
    密码:<input type="password" id="pwd">
    <input type="button" id="login_btn" value="ajax登录提交">
</form>

// @@@@@{# js #}@@@@
$("#login_btn").click(function () {
    // 基于 Ajax 的登录验证
    $.ajax({
        url:"/login/", //请求URL
        type:"post",   // 请求的方式(注意forbiden报错,解决方案后面讲)
        data:{         // data传送的数据格式符合标准的http协议
            user:$("#user").val(),
            pwd:$("#pwd").val(),
        }, // 发送给服务器的数据
        success:function (data) {  // 执行成功之后的回调函数,得到服务器的数据
            console.log(data);     // 服务器传递的是一个json字符串
            console.log(typeof data);
            var res = JSON.parse(data); // 反序列化成js能操作的数据结构 object{}
            console.log(res);
            console.log(typeof res);

            if (res.user){
                // 跳转功能
                location.href = "http://www.baidu.com"
            }else{
                alert(res.msg)
            }
        }
    });
})

"""python app01/views.py"""
def login(request):
    if request.method == "POST":
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")
        user_obj = User.objects.filter(name=user,pwd=pwd).first()
        res = {"user":None,"msg":None}
        if user_obj:
            res["user"] = user_obj.name
        else:
            res["msg"] = "user or passward is wrong!"
        import json
        return HttpResponse(json.dumps(res))  # 使用json模块进行序列化
    else:
        return HttpResponse("OK")

5.基于form表单的文件上传

{# html #}
{# 基于form表单的文件上传 必须要enctype为multipart/form-data,否则只能上传文件名!#}
{# enctype 决定数据的编码类型 #}
<form action="/fileput/" method="post" enctype="multipart/form-data">
    用户名 <input type="text" name="user">
    头像 <input type="file" name="avatar">
    <input type="submit">
</form>

// @@@@@{# js #}@@@@
none

"""python app01/views.py"""
def file_put(request):
    """
    request.FILES
    存放上传的文件
    """
    if request.method == "POST":
        print("FILES",request.FILES)  # 获取的文件对象列表 FILES <MultiValueDict: {'avatar': [<InMemoryUploadedFile: 3.jpg (image/jpeg)>]}>
        print("POST",request.POST)  # 获取的文件对象列表 POST <QueryDict: {'user': ['fgsfdg']}>
        file = request.FILES.get("avatar") #有name属性
        with open(file.name,"wb") as f:
            for line in file:
                f.write(line)
    return HttpResponse("OK")

6.请求头之contentType

{# html #}
{# 请求头之contentType enctype="application/x-www-form-urlencoded"是默认值#}
{# 此时请求头contentType为urlencoded 对应请求体格式如 a=1&b=2&c=3#}
<form action="/contenttype/" method="post" enctype="application/x-www-form-urlencoded">
    cType用户名:<input type="text" id="user-con">
    cType密码:<input type="password" id="pwd-con">
    <input type="submit" >
</form>

// @@@@@{# js #}@@@@
none

"""python app01/views.py"""
def contentType(request):
    """请求
    请求首行
    请求头
    ...
    ContentType:urlencoded 对应from表单中enctype="application/x-www-form-urlencoded"
    对应的请求体为普通的键值对(比如 a=1&b=2&c=3)
    如果ContentType为data类型,则上传的文件以其他的方式编码。
    (还有一种为text/plain基本不用)

    """
    return HttpResponse("contentType")

7.基于Ajax的数据上传

{# html #}
<input type="button" class="ajax-btn" value="Ajax">

// @@@@@{# js #}@@@@
$(".ajax-btn").click(function () {
    {#contentType请求头 指定数据以什么编码方式封装数据#}
    $.ajax({
        url:"/contenttype/",
        type:"post",
        data:{   // 默认请求头contentType为urlencoded(可以对应于form表单enctype="application/x-www-form-urlencoded")
            a:1, // 数据对应的编码格式为键值对
            b:2,
        },
        success:function (data) {

        }
    });
})

"""python app01/views.py"""
def contentType(request):
    return HttpResponse("contentType")

8.ajax传递json数据

{# html #}
<input type="button" class="btn-json" value="btn-json">

// @@@@@{# js #}@@@@
$(".btn-json").click(function () {
    $.ajax({
        url:"/ajaxjson/",
        type:"post",
        contentType:"application/json", // 指定传输数据为json编码格式
        data:JSON.stringify({  // 序列化成json数据
            a:1,
            b:2,
        }),
        success:function (data) {

        }
    });
})

"""python app01/views.py"""
def ajaxJson(request):
    """
    请求首行
    请求头
    ...
    ContentType:json
    请求体 {"a":"1","b":"2"}
    ------------------------------------------

    request.body
    存放请求报文-->请求体中的原数据
    当contentType == json时
        request.body的数据的格式为b{"a"=1,"b"=2}
        request.POST的数据为空

    当contentType == urlencoded时(或者data)
        request.body的数据的格式为b"a=1&b=2"
        request.POST的数据为字典<QueryDict:{'a'=['1'],'b'=['2']}>

    """
    if request.method == "POST":
        import json
        data = json.loads(request.body)
        print(request.body) # b'{"a":1,"b":2}'
        print(request.POST) # <QueryDict: {}>
        print(data)         # {'a': 1, 'b': 2}

    return HttpResponse("OK")

9.基于ajax的文件上传

{# html #}
<form action="">
    用户名 <input type="text" id="afu">
    头像 <input type="file" id="afa">
    <input type="button" id="afb" value="ajax文件上传">
</form>

// @@@@@{# js #}@@@@
$("#afb").click(function () {
    // 涉及到文件的上传必须按照如下方式操作
    var formdata = new FormData(); // 编码等由FormData对象自己处理
    formdata.append("user",$("#afu").val());
    formdata.append("avatar",$("#afa")[0].files[0]);
    // $("选择器")[0].files[0] 拿到input type=file所选择的文件

    $.ajax({
        url:"/ajaxfile/",
        type:"post",
        contentType:false, // 不指定文件的编码方式(因为当前的数据格式是自己选的)
        processData:false, // 对数据不做预处理
        data:formdata,
        success:function (data) {
            console.log(data)
        }
    });
})

"""python app01/views.py"""
def ajaxFile(request):
    print("body",request.body) # 源请求体(或者非请求体)数据。
    print("POST",request.POST) # POST <QueryDict: {'user': ['egon']}>
    print("File",request.FILES) # <MultiValueDict: {'avatar': [<InMemoryUploadedFile: 图片1.jpg (image/jpeg)>]}>
    return HttpResponse("OK")

posted @ 2018-08-04 16:28  哈哈大圣  阅读(86)  评论(0编辑  收藏  举报