Ajax sends json format data and sends files (FormData) and its own serialization component: serializers

Posted by max101 on Sun, 06 Mar 2022 15:56:31 +0100

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

get request data is directly placed in the url? hinder

url?usernmae=junjie&password=123...

How post requests can be sent to the backend

  • form request
  • ajax request

Coding format of front and rear transmission data

  • urlencoded
  • formdata
  • json

Research form: the default data encoding format is (urlencoded)

Conclusion: Django will automatically parse and encapsulate the data in urlencoded format into request In post.

So what data type is the file?

Conclusion: if the encoding format is changed to form data, the ordinary key value pairs will still be resolved to request Post, but the file type format is resolved to request Files.

Django carries out secondary encapsulation. The back-end does different coding analysis in the back-end for different coding formats and puts them into different methods.

The form form can only send urlencoded and formdata.

So what data format is Ajax?

Conclusion: the default is urlencoded, and the data format is username = Junjie & age = 20. All back ends need request Post accept data

ajax sends JSON format data

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

JSON. The stringify front end converts the data into JSON format and contentType:'application/json' specifies the character encoding format

<script>
    $('#d1'). Click (function() {/ / button triggers a click event
        $.ajax({
            url:'',
            type:'post',
            data:JSON.stringify({'username':'junjie','age':18}),//The data also needs to be converted to JSON format.
            contentType:'application/json',//Specifies the character encoding format
            success:function (){

            }
        })
    })
</script>

Deduce the request in the encoding format (contentType) of the front and rear end transmission data Post can only receive formats such as username = Junjie & age = 18, so can you deduce the JSON returned by the front end in reuqest Definitely not found in post.

Code verification:

def ab_ajax(request):
    print(request.POST)
    return render(request,'ab_ajax.html')

Add: how to judge whether the current request is an ajax request?

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

What is the data transmission format based on the network?

Secondary format.

def ab_ajax(request):
    if request.is_ajax():
        # print(request.is_ajax())
        print(request.body) # b'{"username":"junjie","age":18}'
    return render(request, 'ab_ajax.html')

The back end gets the JSON format string in binary format. Django needs manual processing for JSON format data backend.

How does the backend handle json format strings

import json
def ab_ajax(request):
    if request.is_ajax():
        # print(request.is_ajax())
        # print(request.body)
        # json_bytes = request.body  # Get the binary json format data sent from the front end
        # json_str = json_bytes.decode('utf8') # Decoding, utf8 format
        # json_loads = json.loads(json_str) # Deserialize to initial data format
        # print(json_loads) # {'username': 'junjie', 'age': 18}
        
        json_bytes = request.body
        json_dict = json.loads(json_bytes)
				print(json_dict) # {'username': 'junjie', 'age': 18}
        # json. If a binary data is passed in the brackets of loads, it will be automatically decoded and then serialized
    return render(request, 'ab_ajax.html')

In summary, the following points should be paid attention to when sending json format data by ajax:

  • The contentType parameter is specified as: application/json
  • The data must be real json format data
  • Django backend will not process json format data, so it needs to go to request Body get and process

Ajax send file

ajax sends files with the help of js built-in object FormData

<script>
    //Click the button to send normal key value pairs and file data to the back end
    $('#d4').click(function (){
        //1. Use FormData built-in object
        let obj = new FormData();
        //2. Add common key value pairs
        obj.append('username',$('#d1').val()); //val() / / get the current value of the first matching element, which is equal to value()
        obj.append('password',$('#d2').val());
        //3. Add a file object, $('#d3') takes the index 0, turns it into a native jQuery object, that is, a native label object, and then uses files[0] to obtain the file object passed by the user
        obj.append('myfile',$('#d3')[0].files[0])
        //4. Send the object to the back end based on ajax
        $.ajax({
            url:'',
            type:'post',
            data:obj, //Just put the object in data directly
            // ajax send file must specify two parameters
            contentType:false, //Tell the browser that it doesn't need any coding, and the Django backend can automatically recognize the formdata object,
            processData: false, //Tell the browser not to process the data and send it to the back end intact.

            success:function (args){}
        })
    })
</script>
def myfile(request):
    if request.is_ajax():
        if request.method == 'POST':
            print(request.POST)  
            # <QueryDict: {'username': ['junjie'], 'password': ['123']}>
            print(request.FILES)  
            # < multivaluedict: {myfile ': [< inmemoryuploadedfile: screenshot 2022-03-02 22.19.54. PNG (image / PNG) >]} >

    return render(request, 'myfile.html')

The django back end will automatically recognize the formdata object and prevent the data returned by the front end from entering the corresponding request.

In conclusion, the following points should be paid attention to when sending files via ajax:

  • You need to use the built-in object FormData to send ordinary key value pairs and files

      obj.append('username',$('#d1').val());
    obj.append('password',$('#d2').val());
    obj.append('myfile',$('#d3')[0].files[0])
    
  • Two key parameters need to be specified

    contentType: false
    processData: false
    
  • Django backend can directly recognize the formdata object, and can automatically parse and encapsulate the internal ordinary key value pairs into your request In post, the file data object is automatically parsed and encapsulated into reuqest In files

Django's own serialization component (drf as bedding)

With the help of template syntax, the front end displays data objects.

However, the front end can display the user object with the help of template syntax. If the front end is not Django framework and the front end is separated from the front end, the front end cannot rely on template syntax at this time, so the front end and back end interaction need to be carried out manually, and the front end and back end interaction need to use JSON format.

Construct the back-end data structure as a list set DICTIONARY [{}, {}, {}...], Why construct a list dictionary?

Firstly, there are multiple data sets. The list dictionary has corresponding data at the back end, and there are also corresponding data in JSON and JS, which can just realize the front-end and back-end interaction. JSON can serialize the list format, and the dictionary format can also be used. After deserialization, the front-end JS can get the array set of custom objects one by one, and then get the custom objects one by one through the for loop The value can be obtained by clicking.

Back end logic code:

def gender(request):
    user_queryset = models.User.objects.all()
    user_list = []
    for i in user_queryset:
        tmp = {
            'pk':i.pk,
            'username':i.username,
            'age':i.age,
            'gender':i.get_gender_display() # models. The choice parameter is used for py gender, and the value method is changed.
        }
        user_list.append(tmp)
    return JsonResponse(user_list,safe=False)

At this time, the data format returned to the front end is a list dictionary, in which there are key value pairs.

For the front-end and back-end separation project, the back-end should process and sequence the data code to the front-end.

The above code is to manually change the data type to JSON, but do you want to manually if there are hundreds of data?

Module: from Django Core import serializers to automatically program data into json format strings.

from django.core import serializers


def gender(request):
    user_queryset = models.User.objects.all()
    res = serializers.serialize('json', user_queryset)
    return HttpResponse(res)

The back-end write interface is to use the serialization group price to render data and write an interface document. For example, tell the front-end what the number in the gender represents.

Topics: Ajax