The 8th meeting of django framework

Posted by DirtySnipe on Sat, 26 Feb 2022 05:46:45 +0100

The 8th meeting of django framework

Introduction to AJAX

AJAX (Asynchronous Javascript And XML) is translated into Chinese as "Asynchronous Javascript And XML". That is, use Javascript language to interact asynchronously with the server, and the transmitted data is XML (of course, the transmitted data is not just XML).

AJAX is not a new programming language, but a new way to use existing standards.

The biggest advantage of AJAX is that it can exchange data with the server and update some web pages without reloading the whole page. (this feature gives users the feeling that they complete the request and response process unconsciously)

AJAX does not require any browser plug-ins, but requires users to allow JavaScript to execute on the browser.

  • Synchronous interaction: after the client sends a request, it needs to wait for the server to respond before sending the second request;
  • Asynchronous interaction: after the client sends a request, it can send a second request without waiting for the end of the server response.

Add: only the Ajax version after jQuery encapsulation is introduced here (the native version is complex and generally not used in actual projects). Therefore, when using Ajax in front-end pages, you need to ensure that jQuery is imported

Ajax benefits

  • AJAX uses JavaScript technology to send asynchronous requests to the server;
  • AJAX requests do not need to refresh the entire page;
  • Because the server response content is no longer the whole page, but part of the content in the page, AJAX performance is high;
  • Two key points: 1 Local refresh, 2 Asynchronous request

There are four ways to send requests to the back end:

  1. Enter the url directly into the browser address bar and press enter to GET the request
  2. a href attribute GET request of tag
  3. from form GET request / POST request
  4. ajax GET request / POST request

Implementing Ajax with jQuery

  • Make a simple adder based on ajax dynamic request

Effect achieved:

  • Front end core code:
<p><input type="text" id="d1">+
    <input type="text" id="d2">=
    <input type="text" id="d3"></p>
<p> <button id="btn">Submit</button> </p>


<script>
    $('#btn').on('click',function () {
        {#Send to back end ajax request#}
        $.ajax({
            {#1. Specify which backend to send to ajax request#}
            url:'', // Do not write is to submit to the current address
            {#2. Request mode#}
            type:'post',  // Specify the submission type. The default is get request
            {#3. data#}
            data:{'v1':$('#d1').val(),'v2':$('#d2').val()}, / / get values dynamically
            {#4. Callback function#}
            success:function (args) { // args is a formal parameter returned by the backend
                 $('#d3').val(args) / / add the value put back by the back end to the result box
            }


        })
    })

</script>
  • Back end core code
def sum(request):
    if request.method == 'POST':
        # print(request.POST)  <QueryDict: {'v1': ['12'], 'v2': ['12']}>
        v1 = request.POST.get('v1')
        v2 = request.POST.get('v2')
        v3 = int(v1)+int(v2)
        return HttpResponse(v3)
    return render(request,'sum.html')
  • supplement
HttpResponse The returned object can only be string or number type. If other types of data,
The list is like a dictionary in the following way:
back-end:    
    d = {'code':1000,'msg':v3}
    1. Manual serialization
    import json
    return HttpResponse(json.dumps(d))  # The data returned to the front end is in json format, which needs to be deserialized by the front end
	Front end deserialization:
        1. Manual deserialization
        	JSON.prase(arg)
        2. Automatic deserialization
    		dataType:'JSON'   # Automatic deserialization of parameters in ajax
	2. use JsonResponse object
    return JsonResponse(d)		# Recommended. An object is returned to the front end


summary:
    For backend if yes HttpResponse The returned data callback function is not automatically deserialized
    If the backend directly uses JsonResponse The returned data callback function will automatically help you deserialize

Encoding format (contentType) of front and rear end transmission data

This paper mainly studies the coding format of post request data

get request data is the data url directly after the url? username=xxx&password=123

  • How post requests can be sent to the backend
    1. Form form
    2. ajax request
  • Coding format of front and rear transmission data
    1. urlencoded
    2. formdata
    3. json
  • Research from form conclusion
    1. The encoding format of the form is urlencoded
      Data format: username = XXX & password = 123
    2. django backend will automatically parse and encapsulate the data in urlencoded format into request In post
    3. If the encoding format is changed to formdata, the ordinary key value pairs will still be parsed to requests In post, parse the file to request In files
    4. The form cannot send data in json format

Supplement:

1. form Modify form coding format and modify parameters:
	enctype="multipart/form-data"   // formdata encoding format, the transmission file must be changed
  • Research ajax conclusion

    1. The default encoding format is urlencoded

      Data format: username = XXX & password = 123

    2. django backend will automatically parse and encapsulate the data in the rulencoded encoding format into request In post

Ajax sends json format data

be careful:

  • When transmitting data at the front and rear ends, make sure that the coding format is consistent with the real format of the data (inconsistent)

  • django will not do any processing for json format data

  • reuqest object method supplement

    request.is_ajax()  # Determine whether the current request is an ajax request and return a Boolean value
    

Front end ajax sends json format data core code

$.ajax({
    url:'',
    type:'post',
    data:JSON.stringify({'username':'xxx','age':18})
	contentType:'application/json',
    success:function (args) {
    }
})

Back end receives json format data core code

because django in the light of json Format data will not be processed,You need to decode it yourself
def ab_json(request):
    if request.is_ajax():
        json_str = request.body  # b'{"username":"xxx","age":18}'
        # json. If a binary format data is passed in the brackets of loads, it will be automatically decoded and deserialized internally
        # Note: the system default character code will be selected by default for character coding. It is better to use encoding to specify the character code
        json.loads(json_str,encoding='utf8')  
    return render(request,'ab_file.html')

Front end ajax sending file data core code

<script>
    // Click the button to send normal key value pairs and file data to the back end
    $('#d4').on('click',function () {
        // 1. You need to use the FormData built-in object first
        let formDateObj = new FormData();
        // 2 add normal key value pairs
        formDateObj.append('username',$('#d1').val());
        formDateObj.append('password',$('#d2').val());
        // 3 add file object
        formDateObj.append('myfile',$('#d3')[0].files[0])
        // 4 send the object to the backend based on ajax
        $.ajax({
            url:'',
            type:'post',
            data:formDateObj,  // Just put the object directly behind the data

            // ajax sends files with two parameters that must be specified
            contentType:false,  // Without any coding, the django backend can automatically recognize the formdata object
            processData:false,  // Tell your browser not to do anything with your data

            success:function (args) {
            }
        })


    })
</script>

Back end receives json format data core code

def ab_file(request):
    if request.is_ajax():
        if request.method == 'POST':
            print(request.POST)
            print(request.FILES)
    return render(request,'ab_file.html')

summary:
    1. The front end needs to take advantage of built-in objects FormData
    2. Add common key value pair method
    	formDateObj.append('username',$('#d1').val());
        formDateObj.append('password',$('#d2').val());
        
	3. Add file object
    	formDateObj.append('myfile',$('#d3')[0].files[0])
    	1. Two key parameters need to be specified
        	contentType:false,
 			processData:fasle
             
	4. django The back end can directly recognize formdata Object and can automatically parse and encapsulate the internal common key value pairs into request.POST The file data is automatically parsed and encapsulated into request.FILES in            

django's own serialization component

from django.core import serializers

def ab_ser(request):
    user_queryset = models.User.objects.all()
    # serialize
    res = serializers.serialize('json',user_queryset)
    '''serializers The component automatically turns the data into json Format string, and the internal is very comprehensive'''
    return HttpResponse(res)

'''
Serialized data format
[
{   "model": "app01.user", 
    "pk": 1, 
    "fields": {"username": "xxx", "age": 15, "gender": 1}}, ]
'''

ajax combined with sweetinsert to realize the deletion of secondary confirmation

  • Front end core code

    <script>
        $('.del').on('click',function () {
            // Store the current label object first
            let currentBtn = $(this);
            // Secondary confirmation pop-up
            swal({
              title: "Are you sure you want to delete it?",
              text: "You should consider cleaning up. You may need to carry your bag and run away!",
              type: "warning",
              showCancelButton: true,
              confirmButtonClass: "btn-danger",
              confirmButtonText: "Yes, I will delete it!",
              cancelButtonText: "forget it,forget it!",
              closeOnConfirm: false,
              closeOnCancel: false,
              showLoaderOnConfirm: true  // Wait for dynamic effects
            },
            function(isConfirm) {
              if (isConfirm) {
                    // Send an ajax request to the back end to delete the data, and then pop up the prompt box below
                    $.ajax({
                        {#url:'/delete/user/' + currentBtn.attr('delete_id'),  // 1. Method of transferring primary key value 1#}
                        url:'/delete/user/',  // 2 put it in the request body
                        type:'post',
                        data:{'delete_id':currentBtn.attr('delete_id')},
                        success:function (args) {  // args = {'code':'','msg':''}
                            // Judge the response status code and then do different processing
                            if(args.code === 1000){
                                swal("Deleted!", args.msg, "success");
                                // 1. The LowB version directly refreshes the current page
                                {#window.location.reload()#}
                                // 2. Dynamic refresh using DOM operation
                                currentBtn.parent().parent().remove()
                            }else{
                                swal('finished','A location error has occurred','info')
                            }
                        }
    
                    })
    
              } else {
                swal("Coax", "Don't say I know you", "error");
              }
            });
        })
    
    </script>
    
  • Back end core code

    def book_del2(request):
        if request.is_ajax():
            if request.method == 'POST':
                del_id = request.POST.get('del_id')
                back_dic = {"code": 1000, 'msg': del_id}
                models.Book.objects.filter(pk=del_id).delete()
                return JsonResponse(back_dic)
    

Topics: Javascript Django Ajax