The third stage of Python learning AJAX

Posted by shailendra on Fri, 21 Jan 2022 00:16:10 +0100

1.AJAX

1. What is AJAX

​ Asynchronous Javascript And Xml
Asynchronous JS and xml(EXtensible Markup Language)

Send the request to the server asynchronously through JS and receive the response data

Synchronous access:
When the client sends a request to the server, the browser can only wait in the process of processing, which is inefficient

Asynchronous access:
When the client sends a request to the server, the client can do other operations during the processing of the server without waiting all the time

AJAX benefits:

​ 1. Asynchronous access

​ 2. Local refresh

Use occasion:

​ 1. Search suggestions

​ 2. Form Validation

​ 3. Front and rear end separation

2.AJAX core object - asynchronous object (XMLHttpRequest)

1. What is XMLHttpRequest [xhr for short]

It is called "asynchronous object", instead of the browser sending asynchronous requests to the server and receiving responses

[xhr is provided by JS]

2. Create asynchronous object (xhr)

​ 1. IE7 +, chrome, Firefox, Safari, opera) - > call XMLHttpRequest to generate xhr object

​ 2. In IE lower version browsers (IE6 and below) - > call ActiveXObject() to generate xhr

<script>
	if(window.XMLHttpRequest){
		//Supports XMLHttpRequest
		var xhr = new XMLHttpRequest();
	}else{
		//XMLHttpRequest is not supported. Use ActiveXObject to create asynchronous objects
		var xhr = new ActiveXObject("Microsoft.XMLHTTP");
	}
</script>

3. Members of XHR

​ 1. Method - open()

Role: create request

Syntax: open(method,url,asyn)

Parameters:

Method: request method. The value is' GET 'or' POST '

url: request address, string

asyn: whether to adopt asynchronous mode - true: asynchronous / false: synchronous

​ ex: xhr.open('GET','/server',true);

​ 2. Method - send()

Function: notify xhr to send a request to the server

Syntax: send(body)

Parameters:

GET request: the value of body is null - > send (null)

POST request: the value of body is request data - > send ("request data")

​ 3. Properties - readyState

Function: xhr status, which indicates the interaction between xhr and the server through different xhr statuses

5 different states are represented by 5 values of 0-4

stateexplain
0The proxy was created, but the open() method has not been called.
1The open() method has been called.
2The send() method has been called and the response header has been received
3Downloading; The responseText property already contains some data.
4Download operation completed

​ 4. Properties - responseText

Function: response data

​ 5. Properties - status

Function: server side response status code

Statusexplain
200Indicates that the server correctly handles all requests and gives responses
404The requested resource does not exist
500Server internal error

​ 6. Event - onreadystatechange

Function: the operation to be triggered whenever the readyState of xhr changes;

Also called callback function; The response data can be obtained only when the readyState value is 4 and the status value is 200

3.AJAX operation steps

1.GET request

//1. Create xhr request
var xhr = createXhr();
//2. Create request - open()
xhr.open('GET',url,asyn[true|false])
//3. Set callback function - onreadystatechange
xhr.onreadystatechange = function(){
    if(xhr.readyState == 4 && xhr.status == 200){
        //Receive response
        xhr.responseText;
    }
}
//4. Send request
xhr.send(null);

//Note: if there is a request parameter - URL, splice the query string QueryString
//ex: xhr.open('get','/url?key=value&key=value',asyn)

2.POST request

//1. Create xhr request
var xhr = createXhr();
//2. Create request - open()
xhr.open('post',url,asyn[true|false])
//3. Set callback function - onreadystatechange
xhr.onreadystatechange = function(){
    if(xhr.readyState == 4 && xhr.status == 200){
        //Receive response
        xhr.responseText;
    }
}
//4. Set content type;
//The default content type of ajax post is "text/plain;charset=utf-8"
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
//5. Send request
xhr.send('Request data');
//The request data is the same as the query string "uname = guoxiaonao & age = 18"

Note: post in django needs to pass csrf_token, otherwise, the response code 403 is triggered to refuse access;

Get CSRF_ The token method is as follows

var csrf=$("[name='csrfmiddlewaretoken']").val();
#After obtaining the token, put it in the post body data and submit it together

2.jquery support for ajax

$.ajax({})

Properties in parameter object:
	1.url : A string representing the address of an asynchronous request
	2.type : String, request mode, GET or POST
	3.data : Parameters passed to the server side
		Can be a string:"name=sf.zh&age=18"
		It can also be js object:
			{
				name:"sf.zh",
				age:18
			}
	4.dataType : String, the format of the data returned in response
		1.'html'
		2.'xml'
		3.'text' 
		4.'script'
		5.'json'
		6.'jsonp' : About cross domain response formats
	5.success:Callback function, the operation to be executed when the request and response are successful
	6.error : Callback function, the operation to be performed when the request or response fails
	7.beforeSend : Callback function, sending ajax Action performed before the request, if return false,Then terminate the request
    8.contentType : When a requestor has data submission, the submission method is indicated. The default value is'application/x-www-form-urlencoded; charset=UTF-8'

3.JSON

1.JSON introduction

​ JSON:JavaScript Object Notation

Definition: is a lightweight data exchange format. A grammar subset of JS; Data is stored and represented in a text format completely independent of the programming language. The concise and clear hierarchy makes JSON an ideal data exchange language. It is easy for people to read and write, but also easy for machine analysis and generation, and effectively improves the network transmission efficiency.

Scenario: in ajax, it is allowed to build response data in complex format into JSON format for response

2.JSON performance

1.JSON represents a single object

​ 1. Use {} to represent a single object

​ 2. Use the form of key:value in {} to represent attributes (data)

​ 3.Key must be quoted with ''

​ 4. If value is a string, it also needs to be quoted with ""

    var obj = {
            "name":"Miss Wang",
            "age" : 30,
            "gender" : "Unknown"
    }

2.JSON represents an array

​ 1. Use [] to represent an array

​ 2. Arrays are allowed to contain several JSON objects or strings

​ 1. Use JSON arrays to represent several strings

	var arr = ["Wang Weichao","Mrs. Wang","Wang Xiaochao"];

​ 2. Using JSON arrays to represent several objects

    var arr = [
        {
            "name":"Miss Wang",
            "age":30,
            "gender":"male"
                            },
        {
            "name":"Mrs. Wang",
            "age":28,
            "gender":"male"
                            }
        ];

3. Use jq's each() to iterate over the array

Review traversal array in JS

	var a = [{"name":"guoxiaonao", "age": 18 }, {"name":"guoxiaonao2", "age": 22}];
	
	for (var i = 0 ; i < a.length ; i++ ){
		var obj = a[i];
		console.log('name is ' + obj.name);
		console.log('age is '+ obj.age);
	}

​ 1.$(arr).each();

$arr: array in jquery

        //Syntax:
        $(arr).each(function(index,obj){
            index:The subscript of the element traversed
            obj:Traversed elements
        });

​ 2.$.each()

        //Syntax:
        $.each(arr,function(index,obj){});
        arr : js Normal array in

4. Background processing JSON

Query the data in the background, convert it into JSON format string, and then respond to the front end

​ 1. Get data in the background first

The allowed types are: tuple | list | dictionary

​ 2. Convert data to JSON format string in the background

​ 3. Respond to JSON formatted strings in the background

5. JSON processing in Python

import json
#Serialization - python object becomes json string
jsonStr = json.dumps(tuple|list|Dictionaries)
#Deserialization - the json string becomes a python object
py_obj = json.loads(jsonStr)

JSON processing in Django

#Method 1 uses the serialization class provided in Django to complete the conversion from QuerySet to JSON string
from django.core import serializers
json_str = serializers.serialize('json',QuerySet)
return HttpResponse(json_str)

#Method 2
d = {'a': 1}
return JsonResponse(d)

6. JSON processing in the front end

#serialize
JSON character string JSON.stringify(JSON object)

#Deserialization
JSON object=JSON.parse(JSON character string)

practice:

1. Click the button on the page to send an ajax request to the back end to obtain data

2. Display the user data returned from the back end to the page

4. Cross domain

1. What is cross domain

Cross domain: the process of sending requests to non homologous web pages is cross domain

Browser homology policy:
Homology: in multiple addresses, the same protocol, the same domain name and the same port are considered to be the same"Homology"
stay HTTP In, the same source address must be used to send requests to each other, and the non same source rejects the request(<script>and<img>except). 

http://www.tedu.cn/a.html
http://www.tedu.cn/b.html
 The above address is "Homology"

http://www.tedu.cn/a.html
https://www.tedu.cn/b.html
 Not because of different protocols"Homology"

http://localhost/a.html
http://127.0.0.1/a.html
 Not because of different domain names"Homology"

http://www.tedu.cn:80/a.html
http://www.tedu.cn:8080/b.html
 Not because of different ports"Homology"

2. Solution

adopt

3. Cross domain of jquery

jsonp - json with padding
 User passes a callback The parameter is given to the server, and this parameter will be used when the server returns data callback Parameters are wrapped as function names JSON data

ex:
	Current address: http://127.0.0.1:8000/index
    To access: http://localhost:8000/data?callback=xxx

	$.ajax({
		url:'xxx',
		type:'get',
		dataType:'jsonp',//Specify as cross domain access
		jsonp:'callback',//Defines the parameter name of the callback to get the function name passed by the callback
		jsonpCallback:'xxx' //Defines the callback function name of jsonp
	});

	$.ajax({
		url:'xxx',
		type:'get',
		dataType:'jsonp',//Specify as cross domain access
        success: function(data){}
	});



Topics: Python Ajax