Django ajax 简单介绍

AJAX

Asynchronous Javascript And XML是 "异步Javascript和XML"。即使用 Javascript 语言与服务器进行异步交互,传输的数据为XML。

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

优点:
AJAX使用Javascript技术向服务器发送异步请求;
AJAX无须刷新整个页面;
因为服务器响应内容不再是整个页面,而是页面中的局部,所以AJAX性能高;
缺点:
AJAX并不适合所有场景,很多时候还是要使用同步交互;
AJAX虽然提高了用户体验,但无形中向服务器发送的请求次数增多了,导致服务器压力增大;
因为AJAX是在浏览器中使用Javascript技术完成的,所以还需要处理浏览器兼容性问题;

大概步骤:
step 1: var xmlhttp=XMLHttperquest()
step 2: xmlhttp.open("")
step 3: xmlhttp.send("name=klvchen") # 请求体的内容如果为 GET 请求则为 send(null)
step 4: if(xmlhttp.readyState=4 && xmlhttp.status=200) # 监听


ajax 发送GET请求

创建一个 Ajax_lesson 项目 和 app01 应用
修改 urls.py 文件

from django.contrib import admin
from django.urls import path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
    path('ajax_receive/', views.ajax_receive),
]

在 tempates 文件夹中添加 index.html 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button onclick="func1()">ajax提交</button>
</body>

<script>
    function createXMLHttpRequest() {
            var xmlHttp;
            try{
                xmlHttp = new XMLHttpRequest();
            } catch (e) {
                try {
                    // 适用于IE6
                    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
                }catch (e) {
                    try {
                        // 适用于IE5.5,以及IE更早版本
                        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                    }catch (e) {

                    }
                }

            }

            return xmlHttp;
        }

    function func1() {
        var xmlhttp = createXMLHttpRequest()
        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                var data = xmlhttp.responseText;
                alert(data);
            }
        }
        xmlhttp.open("GET", "/ajax_receive/", true);
        xmlhttp.send(null);

    }


</script>
</html>

在 views.py 上修改

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request,'index.html')

def ajax_receive(request):
    print('ok')
    return HttpResponse("hello world2")


ajax 发送POST请求

修改 index.html 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button onclick="func1()">ajax提交</button>
</body>

<script>
    function createXMLHttpRequest() {
            var xmlHttp;
            try{
                xmlHttp = new XMLHttpRequest();
            } catch (e) {
                try {
                    // 适用于IE6
                    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
                }catch (e) {
                    try {
                        // 适用于IE5.5,以及IE更早版本
                        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                    }catch (e) {

                    }
                }

            }

            return xmlHttp;
        }

    function func1() {
        var xmlhttp = createXMLHttpRequest()

        xmlhttp.open("POST", "/ajax_receive/", true);
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
       
        xmlhttp.send("name=klvchen");

        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                var data = xmlhttp.responseText;
                alert(data);
            }
        }

    }


</script>
</html>

修改 views.py 文件

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request,'index.html')

def ajax_receive(request):
    if request.method=="POST":
        print("req.POST", request.POST)
    return HttpResponse("hello world2")

在 settings.py 文件中注释

   #'django.middleware.csrf.CsrfViewMiddleware',


原文地址:https://www.cnblogs.com/klvchen/p/10938722.html