Django之原生Ajax操作

Ajax主要就是使用 【XmlHttpRequest】对象来完成请求的操作,该对象在主流浏览器中均存在(除早起的IE),Ajax首次出现IE5.5中存在(ActiveX控件)。

先通过代码来看看Ajax吧!

views.py
from django.shortcuts import render,redirect,HttpResponse
from django import  forms
from django.forms import fields
from app_01 import models

def ajax(request):
    return render(request, 'ajax.html')

def ajax_json(request):
    import time
    time.sleep(3)
    print(request.POST)   #打印request.POST内的内容
    ret = {'code': True , 'data': request.POST.get('username')}
    import json
    return HttpResponse(json.dumps(ret))     #向前台发送ret,利用json.dumps()将ret变为字符串
ajax.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <input type="text"/>
    <input type="button" value="Ajax1" onclick="Ajax1();" />

<form action="/ajax_json/" method="POST" >
        <input type="text" name="username" />
        <input type="text" name="email" />
        <input type="submit" onclick="sumitForm();" value="Form提交"/>
    </form>

<script type="text/javascript" src="/static/jquery-1.12.4.js"></script>
    <script>
function Ajax1(){
            var xhr = getXHR();
            //var xhr = new XMLHttpRequest();         //创建XMLHttpRequest对象
            xhr.open('POST', '/ajax_json/',true);  //指定用post发,发送到ajax_json里,是否异步为true,默认不填也为true
            xhr.onreadystatechange = function(){     //onreadystatechange为回调函数,当匿名函数内的状态发生变化时就会执行,每一次都会执行
                if(xhr.readyState == 4){             //一共5个状态,当状态为4时,启动使其发生变化
                    // 接收完毕
                    var obj = JSON.parse(xhr.responseText); //responseText为返回值,返回html的返回值
                    console.log(obj);
                }
            };
            xhr.setRequestHeader('k1','v1');   //发送GET请求头,利用csrf时使用
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');  //发送post请求时
            xhr.send("name=root;pwd=123");   //发送数据,发送的只能是字符串
        }
</script>
</body>
</html>

点击Ajax1,可以看到请求已经发送过去

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');  //发送post请求时
xhr.send("name=root;pwd=123");   //发送数据,发送的只能是字符串

通过这两行代码,可以知道已经向后台发送了请求

看完这些代码,就差不多知道原生ajax是怎么发送请求的了吧!

那下面就说说原生ajax的方法和属性

1、XmlHttpRequest对象介绍

XmlHttpRequest对象的主要方法:

a. void open(String method,String url,Boolen async)
   用于创建请求
    
   参数:
       method: 请求方式(字符串类型),如:POST、GET、DELETE...
       url:    要请求的地址(字符串类型)
       async:  是否异步(布尔类型)
 
b. void send(String body)
    用于发送请求
 
    参数:
        body: 要发送的数据(字符串类型)
 
c. void setRequestHeader(String header,String value)
    用于设置请求头
 
    参数:
        header: 请求头的key(字符串类型)
        vlaue:  请求头的value(字符串类型)
 
d. String getAllResponseHeaders()
    获取所有响应头
 
    返回值:
        响应头数据(字符串类型)
 
e. String getResponseHeader(String header)
    获取响应头中指定header的值
 
    参数:
        header: 响应头的key(字符串类型)
 
    返回值:
        响应头中指定的header对应的值
 
f. void abort()
 
    终止请求

XmlHttpRequest对象的主要属性:

 

a. Number readyState
   状态值(整数)
 
   详细:
      0-未初始化,尚未调用open()方法;
      1-启动,调用了open()方法,未调用send()方法;
      2-发送,已经调用了send()方法,未接收到响应;
      3-接收,已经接收到部分响应数据;
      4-完成,已经接收到全部响应数据;
 
b. Function onreadystatechange
   当readyState的值改变时自动触发执行其对应的函数(回调函数)
 
c. String responseText
   服务器返回的数据(字符串类型)
 
d. XmlDocument responseXML
   服务器返回的数据(Xml对象)
 
e. Number states
   状态码(整数),如:200、404...
 
f. String statesText
   状态文本(字符串),如:OK、NotFound...

2、跨浏览器支持

XmlHttpRequest
  ·IE7+, Firefox, Chrome, Opera, etc.
ActiveXObject("Microsoft.XMLHTTP")
  ·IE6, IE5

原文地址:https://www.cnblogs.com/zhuifeng-mayi/p/9131727.html