Ajax
What is 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 only XML, but now more json data is used).
- 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.
So what are the advantages of Ajax?
- Asynchronous interaction: after the client sends a request, it can send a second request without waiting for the end of the server response.
- Browser local refresh: exchange data with the server and update some web pages without reloading the whole page.
This is also the biggest feature of Ajax. Without reloading the whole page, it exchanges data with the server and updates part of the web page content. This feature gives users the feeling that it completes the request and response process unconsciously.
For example, the browser is partially refreshed. Take GitHub registration page as an example:
Enter the email address, and the GitHub registration interface dynamically obtains the user's real-time written information. The whole page is not refreshed. It is confirmed with the back end in real time and displayed to the front end in real time. This is local refresh.
In the past, we used to send requests in front and back-end interaction. What are the ways?
- Enter the url in the browser address bar and press enter --- GET request
- a tag href attribute --- GET request
- form -- GET request / POST request
- Ajax --- GET request / POST request
Among them, the from form submission data mode is unified page submission, that is, synchronous interaction. Ajax uses JavaScript technology to send asynchronous requests to the server. It is no longer necessary to refresh the whole page, but only some contents of the page. All Ajax have higher performance.
At present, AJAX is mostly used to encapsulate the version of jQuery, so when using Ajax on the front-end page, you need to ensure that jQuery. XML is imported
Ajax basic syntax:
<script> //Bind a click event to the button first $('#btn').click(function (){ //Send Ajax request from super backend $.ajax({ //1. Specify which backend to send ajax requests to url:'',//Not writing is to submit a request to the current address //2. The request method needs to be specified type:'post', //Do not specify the default get, just lower case. //3. Data, custom object data:{'username':'junjie','password':123}, //4. Asynchronous callback mechanism, callback function: when the result returned by the back end is, it will be triggered automatically, and arg will receive the result returned by the back end success:function (args) { } }) }) </script>
Let's start with a basic example to demonstrate Ajax:
There are three on the page input Box: Enter the numbers in the first two boxes, click the button, and move backward'g End sending ajax Request. The back-end calculates the result, and then returns it to the front-end for dynamic display to the third input Box(The whole process page cannot be refreshed or calculated at the front end)
Front page:
<body> <input type="text" id="d1">+ <input type="text" id="d2">= <input type="text" id="d3"> <p> <button id="btn">spot</button> <!--Click events need to be bound--> </p> </body> <script> //Bind a click event to the button first $('#btn').click(function (){ //Send Ajax request from super backend $.ajax({ //1. Specify which backend to send ajax requests to url:'',//Not writing is to submit a request to the current address //2. The request method needs to be specified type:'post', //Do not specify the default get, just lower case. //3. Data, custom object data:{'username':'junjie','password':123}, //4. Asynchronous callback mechanism, callback function: when the result returned by the back end is, it will be triggered automatically, and arg will receive the result returned by the back end success:function (args) { } }) }) </script>
views.py: backend
def ab_ajax(request): if request.method == 'POST': """ use ajax Submit to the back end post When requested, it is also in request.POST Ordinary key value pairs can be obtained in output: <QueryDict: {'username': ['junjie'], 'password': ['123']}> """ print(request.POST) return render(request, 'index.html')
def ab_ajax(request): if request.method == 'POST': """ use ajax Submit to the back end post When requested, it is also in request.POST Ordinary key value pairs can be obtained in <QueryDict: {'username': ['junjie'], 'password': ['123']}> """ print(request.POST) i1 = request.POST.get('i1') i2 = request.POST.get('i2') # Because the data type obtained is in string form. You need to convert to integer before you can perform logical operations. i3 = int(i1) + int(i2) return HttpResponse(i3) return render(request, 'index.html')
<script> //Bind a click event to the button first $('#btn').click(function () { //Send Ajax request from super backend $.ajax({ //1. Specify which backend to send ajax requests to url: '',//Not writing is to submit a request to the current address //2. The request method needs to be specified type: 'post', //Do not specify the default get, just lower case. //3. Data, custom object //Get the value entered by the user in the input box, using $('id ') Val(), jQuery writing method data: {'i1': $('#d1').val(), 'i2': $('#d2').val()}, //4. Asynchronous callback mechanism, callback function: when the result returned by the back end is, it will be triggered automatically, and arg will receive the result returned by the back end success: function (args) { {#alert(args)#}/ / dynamically render to the third input box through DOM operation console.log(typeof (args)) //string $('#d3').val(args) / / receive the JsonResponse data object and automatically deserialize it. } }) }) </script>
Back end views py
def ab_ajax(request): if request.method == 'POST': """ use ajax Submit to the back end post When requested, it is also in request.POST Ordinary key value pairs can be obtained in <QueryDict: {'username': ['junjie'], 'password': ['123']}> """ d = {'username':'junjie','age':666} return JsonResponse(d) return render(request, 'index.html')
For the backend, if the data returned by HttpResponse is used, the callback function will not automatically deserialize
If the back-end uses the data returned by JsonResponse, the callback function will automatically deserialize
Supplement:
# Parameter code publishing projects also involve dataType:'JSON' When the back end is HttpResponse Returned json Formatted data By default, it will not be deserialized automatically 1.Self manual JSON.parse() 2.to configure dataType parameter