Foreword:
Ajax is a technology that can change part of the content of the webpage without refreshing the webpage. It refers to asynchronous javascript and xml for data interaction with the server. Ajax can be used when submitting a small amount of data to the server. This article talks about It is a native ajax+django application
The benefits of ajax:
- There is no need to refresh the webpage to interact with the server;
- Allows you to update some data on the web page based on user events;
Steps to encapsulate native ajax:
- Create an XMLRequestHttp object;
- Open the link, send the request,
- send parameter
- receive response
1. Create an XMLRequestHttp object;
This is the basis of encapsulating ajax;
let xhr = new XMLRequestHttp()//创建XMLRequestHttp对象
2. Open the link and send the request;
There are two ways to send requests: get and post;
In this step, the same-origin policy should be considered: that is, to ensure the consistency of domain name + protocol + port number
This step is done through open()
xhr.open('请求方式','请求地址')
3. Send parameters
This step is divided into two types according to the different request methods.
//get请求发送参数,一般填的是null即:
xhr.send(null);
//post请求有所不同,
xhr.SetRequestHeaders('Content-Type','application/x-www-form-urlencoded');//这一步是向请求添加http头
xhr.send('name='李四'&age=30');
4. Receive the response
There are two types of responses from the server:
1. responseText: Get data in the form of a string
2. responseXML: Get data in the form of xml
When the server that the request is sent to is readyState, it will change, thus calling onreadystatechange
readyState has the following five states:
0: Indicates that the XMLRequestHttp instance has been generated, but open has not been called;
1: Indicates that the connection has been established and send() has not been called yet, and setRequestHeader() can still be used to set the information of the http request header;
2: Indicates that the send() method has been executed, and the header information and status code have been received
3: Indicates that the data in the body part from the server is being received
4: Indicates that all server data has been received, or this reception failed
//当请求发送的服务器是readyState就会发生改变,从而调用onreadystatechange
xhr.onreadystatechange = () =>{
if(xhr.readystate == 4 && xhr.status == 200){
console.log(xhr.responseText);
}
}
django+ajax total code
1. Create a django project
1. Download the third-party package django-cors-headers, which is used for cross-domain requests
pip install django-cors-headers//下载第三方包
2. Configure the following content in the settings.py file
INSTALLED_APPS = [
'corsheaders'
]
MIDDLEWARE = [
#'django.middleware.csrf.CsrfViewMiddleware',//这个要注释掉
'corsheaders.middleware.CorsMiddleware'//这个是新增的
]
CORS_ORIGIN_ALLOW_ALL = True
3. Download the sub-application and enter it in the console
python manage.py startapp app1//app1是子应用名,可以自定义
4. Register sub-applications
INSTALLED_APPS = [
'app1',
]
5. Configure routing
//配置一级路由
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('app1/',include('app1.urls',namespace='app1'))
]
//配置二级路由
app_name = 'app1'
from django.urls import path
from .views import *
urlpatterns = [
path('index/',index.as_view(),name='index'),
]
6. View function
from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
# Create your views here.
class index(View):
def get(selt,request):
datas = {
'id':1,
'title':'老树昏鸦',
'fanwei': '莫道黄昏',
}
#datas是返回给ajax的数据
return JsonResponse(datas,safe=False)
7. Content written in js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
/**
* 封装ajax
* @param method:请求的方式get还是post
* @param url:请求的地址
* @param params:发送的参数
* @callback 返回响应调用的函数
* */
function ajax(method, url, params = null, calleck) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
if (method.toLowerCase() == 'get') {//判断请求方式
xhr.send(params);
} else {
xhr.setRequestHeader('Content-Type', application / x - www - form - urlencoded);
var str = '';
for (p in params) {
str += `${p}=${params[p]}&`;
}
xhr.send(str);
}
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
calleck(xhr.responseText);
}
}
}
//执行ajax
ajax('get', 'http://127.0.0.1:8000/app1/index/', null, createHtml);
function createHtml(data) {
var data = JSON.parse(data);
console.log(data)
}
</script>
</body>
</html>
If you see the content in the console, it is successful.