ajax基本用法介绍

一、基于jQuery的ajax

此时需要在模板中引用jQuery,ajax的本质是利用浏览器自带的XMLHttpRequest对象并通过jQuery将数据和请求头进行封装再发送。ajax基本使用方法如下:

$.ajax({
        url:'url',
        type:'POST',
        data:{'k1':v1,'k2':v2,},
        dataType:'JSON',
        traditional:true,
        success:function (arg) {
        }
        error:function () {
        }
    })     

整个ajax的内容包含在$.ajax({  })中

第一行url:指定ajax发送给哪个url进行处理,再通过urls.py文件去执行对应的处理函数

第二行type:ajax发送数据的方式,可以是GET或者POST,如果使用POST方法可先注释掉csvf中间件

第三行data:ajax发送的数据,需要是字典格式,且v默认是数字或者字符串

第六行success:表示后台处理函数处理成功后,前端再执行的函数,参数arg表示处理函数的返回值,即HttpResponse的返回值,且只能接收字符串格式

第四行dataType:由于success的function函数默认只能接收字符串格式的返回值,因此如果处理函数需要返回其他格式如字典、列表形式的值,需要通过HttpResponse(json.dumps(返回值))传递给arg,而在ajax中需要再通过JSON.parse(arg)再将返回值还原为原来的格式,而dataType:'JSON'可以省略前端的JSON.parse(arg),直接将返回值通过JSON还原为原来的格式后再传递给arg。

第五行traditional:ajax发送的数据字典的值默认是数字或者字符串,如果值是列表(不能是字典),则需要指定traditional:true

第七行error:例如当指定的url错误、网络错误等,会执行此函数。

ajax不接收处理函数返回的redirect跳转,只会根据函数返回的消息内容主动决定是否做刷新或跳转。

 1.ajax发送get请求

.btn{display:inline-block;background-color: darkgoldenrod;padding: 5px 10px;color: white;cursor: pointer}
……
<a class="btn" onclick="ajaxSubmit3()">点我</a>
……
function ajaxSubmit3() {
    $.ajax({
        url:'ajax1',
        type:'POST',
        data:{'p':123},
        dataType:'json',
        success:function (arg) {
        console.log(arg.status,arg.data)
        }
    })
}
模板和使用ajax发送get请求
def ajax1(request):
    print(request.GET)
    ret = {'status':'success','data':[1,'hello']}
    return HttpResponse(json.dumps(ret))
后台处理函数

     

2.ajax发送post请求

<a class="btn" onclick="ajaxSubmit3()">点我</a>
……
function ajaxSubmit3() {
    $.ajax({
        url:'ajax1',
        type:'POST',
        data:{'p':123},
        dataType:'json',
        success:function (arg) {
        console.log(arg.status,arg.data)
        }
    })
}
View Code
def ajax1(request):
    print(request.POST)
    ret = {'status':'success','data':[1,'hello']}
    return HttpResponse(json.dumps(ret))
后台处理函数

     

二、使用浏览器自带的XMLHttpRequest对象

XMLHttpRequest为浏览器自带的发送数据的对象,使用XMLHttpRequest发送数据时,需要手动加上请求头。

XmlHttpRequest对象的主要方法:

void open(String method,String url,Boolen async)  #用于创建请求
    method: 请求方式(字符串类型),如:POST、GET、DELETE...            
    url:要请求的地址(字符串类型)
    async:  是否异步(布尔类型)

void send(String body)  #用于发送请求
    body: 要发送的数据(字符串类型)

void setRequestHeader(String header,String value)  #用于设置请求头
    header: 请求头的key(字符串类型)
    vlaue:  请求头的value(字符串类型)

String getAllResponseHeaders()  #获取所有响应头
    返回值:响应头数据(字符串类型)

String getResponseHeader(String header)  #获取响应头中指定header的值
    header: 响应头的key(字符串类型)
    返回值:响应头中指定的header对应的值

void abort()  #终止请求
XmlHttpRequest对象主要方法
Number readyState  #状态值(整数)
    0-未初始化,尚未调用open()方法;
    1-启动,调用了open()方法,未调用send()方法;
    2-发送,已经调用了send()方法,未接收到响应;
    3-接收,已经接收到部分响应数据;
    4-完成,已经接收到全部响应数据;
 
Function onreadystatechange
   当readyState的值改变时自动触发执行其对应的函数(回调函数)
 
String responseText
   服务器返回的数据(字符串类型)
 
XmlDocument responseXML
   服务器返回的数据(Xml对象)
 
XmlHttpRequest对象主要属性

1.XMLHttpRequest发送get请求

<a class="btn" onclick="ajaxSubmit2()">点我</a>
……
function ajaxSubmit2() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4)
            console.log(xhr.responseText);
        }
    xhr.open('GET','ajax1');
    xhr.send(null);
}    
模板和使用XMLHttpRequest发送get请求
def ajax1(request):
    print(request.GET)
    print(request.body)
    ret = {'status':'success','data':[1,'hello']}
    return HttpResponse(json.dumps(ret))
后台处理函数

2.XMLHttpRequest发送POST请求

<a class="btn" onclick="ajaxSubmit4()">点我</a>
……
function ajaxSubmit4() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4)
            console.log(xhr.responseText);
    }
    xhr.open('POST','ajax1');
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset-UTF-8');
    xhr.send('p=123;q=456');
}
模板和使用XMLHttpRequest发送post请求
def ajax1(request):
    print(request.POST)
    print(request.body)
    ret = {'status':'success','data':[1,'hello']}
    return HttpResponse(json.dumps(ret))
后台处理函数

①发送post请求时需要先注释掉csvf中间件

②XMLHttpRequest对象xhr状态变化时即xhr.readyState的值变化时,会触发xhr.onreadystatechange。

③如果不为XMLHttpRequest对象设置请求头,那么后台接收到的数据在request.body中,request.POST中没有数据;需要用setRequestHeader()方法为其设置请求头,django才会将接收到的数据同时转化到request.POST中。

④使用send()发送数据时,整体为字符串,使用k=v形式发送,多个数据之间用分号间隔;

   

原文地址:https://www.cnblogs.com/Forever77/p/10783720.html