Django中ajax的GET与POST请求、JavaScript与jQuery

ajax介绍

Ajax(Asynchronous Javascript And XML:异步 JavaScript 和 XML),是指一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。

使用Ajax的最大优点,就是能在不更新整个页面的前提下维护数据。这使得Web应用程序更为迅捷地回应用户动作,并避免了在网络上发送那些没有改变的信息。

但是Ajax可能破坏浏览器的后退与加入收藏书签功能。在动态更新页面的情况下,用户无法回到前一个页面状态,这是因为浏览器仅能记下历史记录中的静态页面。

Ajax的定义

Ajax有最初是由js编写的,后来随着js框架的发展,jq,vue等大型框架都对ajax进行了封装,在这里我们学习两种ajax的编写。

Js ajax

我们看一个简单的ajax案例

首先我们创建如图所示的一个项目:

代码如下: 

# app01/views.py
from django.http import JsonResponse
from django.shortcuts import render


# Create your views here.
def getPage(request):
    '''返回页面'''
    return render(request,'django_ajax_pro.html')

def sendData(request):
    '''
    响应ajax请求,在这里要注意响应的内容是json对象
    '''
    return JsonResponse({"data":"hello world"})
#django_pro5/urls
from django.conf.urls import include, url
from django.contrib import admin

from app01.views import getPage, sendData

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^ckeditor/',include('ckeditor_uploader.urls')),

    url(r'ajaxPro/',getPage),
    url(r'ajaxData/',sendData),
]
<!--templates/django_ajax_pro.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax_js_example</title>
</head>
<body>
    <button onclick="getData()">按我呀</button>
    <script>
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); //Msxml2版本Microsoft浏览器
        }catch (e){
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//Microsoft版本Microsoft浏览器
            }catch (e1){
                xmlhttp = new XMLHttpRequest();//非Microsoft浏览器,如:谷歌、Firefox等
            }
        }
        function updatePage() {
            console.log("+++++++++++++++++++++++++++++++++");
            console.log(xmlhttp.readyState);
            console.log(xmlhttp.status);
            console.log("+++++++++++++++++++++++++++++++++");
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                    var response = xmlhttp.responseText;//返回响应的内容
                    console.log(response)
                }
        }
        function getData() {
            url = "/ajaxData/";
            xmlhttp.open("GET",url,true);
            xmlhttp.onreadystatechange = updatePage;
            xmlhttp.send(null)
        }
        console.log(xmlhttp)
    </script>
</body>
</html>

效果如下:

在这里我们关注上面的代码的几个点

1、在视图当中我们定义了两个函数,这里大家一定要搞明白,ajax是局部提交,首先我们需要有页面承载我们的前端效果,其次在前端发起ajax请求,进行响应的是一个独立的视图,并不是我们承载前端的视图。

2、ajax通常返回的数据是json数据,在老版本的Django当中需要先导入json模块,然后用HTTPRespose进行返回,在新版本django.http下已经封装好了一个叫做JsonResponse的功能,他返回的就是json数据

3、js 编写 ajax 的变化有很多种,但是一定注意他的必要的步骤,我们把刚才的代码拆开看一下

      1. 构建XMLHttpRequest对象

try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); //Msxml2版本Microsoft浏览器
        }catch (e){
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//Microsoft版本Microsoft浏览器
            }catch (e1){
                xmlhttp = new XMLHttpRequest();//非Microsoft浏览器,如:谷歌、Firefox等
            }
        }

      2. 发起请求

function getData() {
            url = "/ajaxData/";
            xmlhttp.open("GET",url,true);
            xmlhttp.onreadystatechange = updatePage;
            xmlhttp.send(null)
        }

       3. 进行回调,响应函数

function updatePage() {
            console.log("+++++++++++++++++++++++++++++++++");
            console.log(xmlhttp.readyState);
            console.log(xmlhttp.status);
            console.log("+++++++++++++++++++++++++++++++++");
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                    var response = xmlhttp.responseText;//返回响应的内容
                    console.log(response)
                }
        }

在掌握了上面的例子之后,我们来解释一些需要记住的常识

Ajax对象readyState的五种状态

状态编号

状态

描述

0

未初始化

(XMLHttpRequest)对象已经创建,但还没有调用open()方法。值为0表示对象已经存在,否则浏览器会报错:对象不存在。 

1

载入/正在发送请求

对XMLHttpRequest对象进行初始化,即调用open()方法,根据参数(method,url,true),完成对象状态的设置。并调用send()方法开始向服务端发送请

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值