Django daily -AJAX

Django daily -AJAX

Introduction to AJAX

First AJAX is a premise without reloading the entire page, the page can be updated technical part, he was not a new programming language, but a new method of using the existing standard is based on a native JavaScript development, he can be used to quickly create dynamic web pages.

AJAX biggest feature is the partial refresh and asynchronous submit, partial refresh, partial refresh the name suggests is possible without refreshing the entire page, while asynchronous task does not require submission after submission is still waiting for the return value of the task can continue to run down the task before submitting the return value, then be received by the callback function, efficiency is very high.

This article is not to do from JS to AJAX explanation, but from a relatively simple point of view, combined with the usage of AJAX and jQuery, AJAX can greatly simplify the amount of code itself, and to achieve more functionality, let's work through an example the specific use AJAX and jQuery combination.

One example of JQ and AJAX

Title follows: write a front page, the page has two input box a calculation formula in which the first input box, display the result in the second input box inside, attention, can not refresh the page, i.e. not by direct assignment way to refresh the page to do, and now we recall what a Django project from scratch, then step by step to complete this requirement

# 首先,创建一个Django项目,注意,目录名不要带中文,这里我们定义项目名为task,第一个应用名为app01
# 然后,在task/urls.py里面写入
# task/urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', views.home),
]

Written after routing, we went inside views.py write method

# app01/views.py
def home(request):
    if request.is_ajax():# 这里判断请求类型是否是AJAX的类型
        if request.method == 'POST':# 判断请求method是否是POST
            t1 = request.POST.get('t1')# 两个判断都通过的话,取请求的t1的value值,t1是在前端home.html里面起的别名,第一个输入框的id为t1
            t1 = eval(t1)   # 去引号,因为从前端传过来的是字符串,不能做运算,去引号之后就会变成一个计算式,把计算式直接传给前端就可以计算
            return HttpResponse(t1)
    return render(request, 'home.html')

Then, we went templates folder create a new html file named home.html, of course, we must first in the head <head>imported in jQuery

# templates/home.html
<head>
<script src="https://code.jquery.com/jquery-3.4.1.js"
</script>
</head>
<body>
计算式
<br>
<input type="text" id="t1">//这里定义一个输入框,用来输入计算式
<button id="b1">计算</button>//按钮,最简单的就是最实用的,我们可以给一个空白的按钮绑定很多我们需要的功能,这里id设为b1,方便下面AJAX调用

<br>
结果
<br>
<input type="text" id="t2">//定义第二个输入框,用来显示得到的结果

<script>//下面就是AJAX和jQuery的结合使用
    $('#b1').on('click', function () {//给按钮绑定一个点击事件,b1是上面定义的button的id
        $.ajax({    //下面就是AJAX需要的参数
            
            // 1.向后端地址发数据,不写默认就是朝当前地址提交
            url: '',
            
            // 2.发送的请求,常用的就是post或get
            type: 'post',
            
            // 3.发送数据的内容
            data: {'t1':$('#t1').val()},
                
            // 4.异步提交的任务 需要通过回调函数来处理,即success就是回调函数,用来接收从后端返回的数据,并做处理
            success: function (data) { //这里data就是后端发给前端的异步提交的返回结果
                {#alert(data);#}
                $('#t2').val(data) //这里给t2输入框赋值,t2是上面给第二个输入框定义的id
            }
        })
    })
</script>
</body>

After the above three documents are finished, the implementation of the entire project, you can get what we want pages and features friends.

AJAX and contentType

contentType, translated as content type, message type, here is one of the parameters of AJAX, its main role is to tell the format type data of the front end of the rear end transmission.

We know that the data form submitted form is the default format urlencoded, what is it this type is characterized by the following?:

username=hello&password=123&age=12It is this, in the form of key-value pairs, and to &connect them, is urlencoded format of data, and this data will django backend data format parsing the results on request.POST packed inside, we just request.POST from which you can get all the information we want.

Of course, we know there is another form form encoding format is formdata, defined way:

<form action="" enctype="multipart/form-data"></form>The urlencoded format with respect to the different places that he can not pass the usual data, can also be used to transfer files, but the difference is, django backend for after formdata format type resolution, file type of data will not put in request.POST inside, but on the inside request.FILES, so we take the time to pay attention to the data.

AJAX default data type is actually urlencoded format.

AJAX pass json format

json format we all know, is a particularly good cross-platform data format, because almost all the languages ​​will be docking json format data write method, it is cross-platform, when will choose the basic json format for data transmission, and, django backend for json data format does not automatically resolve, will request.body intact on the inside, so that we can get the original model as manual data sent to the front, without fear of data loss and distortion, how we use AJAX data format ? become json format and transmit it as follows:

# home.html
<script>
    $('#b1').on('click',function () {
        $.ajax({
            url:'',  
            type:'post', 
            // 1. 告诉后端你当前的数据格式 到底是什么类型,因为我们要转换成json数据,所以就告诉后端我们发的就是json格式数据
            contentType:'application/json',
            // 2. 这里才是真正的把要传到后端的数据转成json格式,关键字为JSON.stringify({})
            data:JSON.stringify({'username':'jason','password':'123'}),

            success:function (data) {  
                alert(data)
            }
        })
    })
</script>

# 后端在处理json数据的时候,常用以下格式
# views.py
import json
def home(request):
     if request.method == 'POST':
        json_bytes = request.body   # 这里从request.body里面拿出json格式的数据
        json_str = str(json_bytes,encoding='utf-8')# 将json格式的数据转换成str字符串类型
        json_dict = json.loads(json_str)    # 对字符串的数据反序列化,得到真正的json的大字典
        print(json_dict,type(json_dict))
    return render(request,'index.html')

AJAX upload files

We know form form to transfer files if needed multipart/form-dataformat, so if you need to transfer files AJAX, is very similar thing, need to use the built-in objects Formdata, this is very powerful built-in objects, you can pass an ordinary key, you can also transfer files, the following we will take a look at the code to Formdata an example of how to write AJAX

# home.html

<input type="file" name="myfile" id="t3">
<script>
$('#b1').on('click',function(){
    //1. 生成一个FormData对象,方便后面操作
    var myFormData = new FormData();
    //2. 向生成的对象里面添加普通值
    myFormData.append($("#t1").val());
    //3. 向生成的对象里面添加文件,其实这里是三步,合并成了一步
        //(1).要先通过jQuery查找到该文件的标签
        //(2).然后把jQuery对象转换成js对象
        //(3).利用原生js对象的方法,直接取到文件的内容
    myFormData.append("myfile",$("#t3")[0].files[0]);
    $.ajax({
            url:'',
            type:'post',
            data:myFormData,  // 直接把前面定义的myFormData对象给data即可
            // ajax传文件的时候,一定要指定两个关键性的参数
            contentType:false,  // 不用任何编码,因为formdata对象自带编码
            processData:false,  // 告诉浏览器不要处理我的数据,直接发给后端就行
            success:function (data) {
                alert(data)
            }
        })
    
})
</script>

Guess you like

Origin www.cnblogs.com/Xu-PR/p/11755174.html