Django environment using Ajax
present (sb for a job etc)
The main goal of AJAX is to provide a more efficient way to use AJAX in theNot refreshing the whole pagein the case of AJAX, exchanging data and updating page content with the server through the backend. With AJAX, you canSend a request to the server and receive a responseAnd thenDynamically updating parts of a page using JavaScript
Simply put, the back-end data is processed and passed to the front-end, and then use js to process or judge the data and then rendered to the front-end
AJAX does not require any browser plug-ins, but it does require the user to allow JavaScript to execute on the browser.AJAX uses asynchronous interactions to communicate with the server.
- Synchronized Interaction:
- After a client makes a request, it needs to wait for the server's response to finish before it can make a second request;
- Asynchronous Interaction:
- After a client makes a request, it doesn't have to wait for the server's response to finish before it can make a second request.
synopsis (of previous events)
Common ways to send requests:
- Directly enter the browser address
url
enter (computer key)-
GET
requesting
-
- a tagged
href
causality-
GET
Request/POST
requesting
-
- Forms
-
GET
Request/POST
requesting
-
- Ajax
-
GET
Request/POST
requesting
-
typical example
intended effect
JS implementation
<body> <input type="text" >+ <input type="text" >=<input type="text" ><br> <button >Click here to calculate the results</button> <script> ('b1').addEventListener('click', function () { var num1 = ('num1').value var num2 = ('num2').value var sum = parseInt(num1) + parseInt(num2) ('num3').value = sum }) </script> </body>
Ajax Implementation
The parameters to be calculated are passed to the backend via data
Then success accepts the data returned by the backend and renders it
<body> <input type="text" >+ <input type="text" >=<input type="text" ><br> <button >Click here to calculate the results</button> <script> ('b1').addEventListener('click', function () { var num1 = ('num1').value var num2 = ('num2').value $.ajax({ {#url: specify the URL of the current data submission, if not write the same as the action of the form form, the default release of the former routing address #} url:'', {#type: request type GET / POST default is GET#} type:'post', {#data: data passed to the backend #} data:{ 'num1':num1, 'num2':num2, }, {#success: callback function that accepts data from the backend #} success:function (data){ (data) ('num3').value = data } }) }) </script> </body>
The backend accepts the data and returns the sum parameter.
def test(request): if == 'POST': data = num1 = ('num1') num2 = ('num2') sum = int(num1) + int(num2) return HttpResponse(sum) return render(request, 'app01/', locals())
Passing data in JSON format
success
Get the data returned by the backend and use the(data)
The data is converted so that it can be used directly with the. Properties
Getting Parameters: ajax will need to pass the data will be converted to json type
(())
: when the backend accepts the data, it needs to get the request body, and then loads manually parses the json data.
<body> <input type="text" >+ <input type="text" >=<input type="text" ><br> <button >Click here to calculate the results</button> <script> ('b1').addEventListener('click', function () { var num1 = ('num1').value var num2 = ('num2').value $.ajax({ {#url: specify the URL of the current data submission, if not write the same as the action of the form form, the default release of the former routing address #} url: '', {#type: request type GET / POST default is GET#} type: 'post', {#data: pass backend data in json format #} data: ({ 'num1': num1, 'num2': num2, }), {#success: callback function that accepts data from the backend #} success: function (data) { var new_data = (data) if (new_data.code != 200) { alert('Illegal data') } else { (data) ('num3').value = new_data.sum } } }) }) </script> </body>
Accept data and returnjson
format data (the callback function here in the main uses thedata.parameters
)
def test(request): if == 'POST': # Extracting json data must be done by getting the request body and manually parsing the JSON data. data = (()) num1 = ('num1') num2 = ('num2') sum = int(num1) + int(num2) # HttpResponse sends a str object to the front-end that needs to be re-converted at success. return HttpResponse(({'code':200,'sum':sum})) return render(request, 'app01/', locals())
Transferring file data
<script> $(document).ready( $("#btn_result").click(function () { let numberOne = $("#number1").val(); let numberTwo = $("#number2").val(); let fileVal = $("#file_input")[0].files[0]; // Ajax carries file data with the help of a third-party formData object. // (1) Instantiate a form object. // Put all the key-value pair data into the form object. let formDataObj = new FormData(); ("numberOne", numberOne) ("numberTwo", numberTwo) ("file", fileVal) (fileVal) (formDataObj) // Send requests based on Ajax $.ajax({ // url: specify the URL of the current data submission, if you do not write the same action as the form form, the default release of the former routing address url: "", // type: request type GET / POST default is GET type: "post", // data: data passed to the backend //(1) The transferred data can be put directly into the form object above. data: formDataObj, //(2) Walking the form object does not allow him to encode the data using encoding contentType: false, // The default encoding is urlencoded //(3) Tell the browser not to do additional processing of the data processData: false, {#data: {'number_one': numberOne, "number_two": numberTwo},#} // success: callback function that accepts data from the backend. success: function (data) { (data) (typeof (data)) // Serialize the data using js's own serialization methods {#let dataVal = (data)#} (typeof (data)) if ( === 200) { $("#result").val() } else { alert("Illegal data") } } }) }) ) </script>
def test(request): if == "POST": # Can be used to determine whether the current request method is Ajax or not. print(request.is_ajax()) # True # print(type(("utf-8")[0])) # Getting normal key-value pair data is only done via the POST method data = print(data) # <QueryDict: {'numberOne': ['2'], 'numberTwo': ['2']}> # Getting the file data in the form object is also done with the help of FILES print() # <MultiValueDict: {'file': [<InMemoryUploadedFile: (image/jpeg)>]}> return JsonResponse({"code": 200, "result": "ok"}) return render(request, "app01/", locals())
Django comes with its own serialization component
What is serialization?
It is the process when I want to extract the data from the database and then convert the data object into data that can be used directly.
Serialize data based on jsonresponse
from import User def get_user(request): # Query all user data user_data_list = [] # At this point the object data is retrieved <QuerySet [<Author: Author object (1)>, <Author: Author object (2)>]> user_queryset = () # Data fields extracted and loaded into lists for user_obj in user_queryset: user_data_list.append({ "username": user_obj.username, "age": user_obj.age, "gender": user_obj.get_gender_display(), }) print(user_data_list) # Return the list to the front end return JsonResponse(user_data_list,safe=False)
[{'username': 'drema', 'age': 18, 'gender': 'female'}, {'username': 'opp', 'age': 28, 'gender': 2}, {'username': 'hope', 'age': 38, 'gender': 'female'}]
Based on Django's own serializers
Need to importserializers
module (in software)
from app01 import models from import serializers def test(request): author = () author_list = ("json", author) print(author_list) return JsonResponse(user_data_list, safe=False)
[{"model": "", "pk": 1, "fields": {"name": "Zhang San", "age": 11, "gender": 2}}, {"model": "", "pk": 2, "fields": {"name": "Li Si.", "age": 19, "gender": 2}}]
Registration Example
# Front end {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!-- pull intojQuery--> <script src="{% static 'js/' %}"></script> <!-- pull intoBootstrap(used form a nominal expression)CSSfile--> <link href="{% static 'css/' %}" rel="external nofollow" rel="stylesheet"> <!-- pull intoBootstrap(used form a nominal expression)JavaScriptfile--> <script src="{% static 'js/' %}"></script> <style> /* Left margin */ .left-section { background-color: dimgrey; width: 25%; height: 100vh; position: fixed; top: 0; left: 0; } /* Right-hand margin */ .right-section { background-color: dimgrey; width: 25%; height: 100vh; position: fixed; top: 0; right: 0; } .d1 { position: fixed; left: 35%; } .form-control:focus { outline: none; box-shadow: 0 0 5px cornflowerblue; } .btn-default + .btn-primary { margin-left: 150px; /* Adjust to desired spacing */ } </style> </head> <body> <div class="left-section"></div> <div class="right-section"></div> <div class="d1"> {# <form action="" method="post">#} <div class="form-group"> <label for="username">user ID</label><br> <input type="text" class="form-control" placeholder="Username"><br> <hr> </div> <div class="form-group"> <label for="pwd">cryptographic</label><br> <input type="password" class="form-control" placeholder="Password"><br> <hr> </div> <div class="form-group"> <label for="pwd2">再次输入cryptographic</label><br> <input type="password" class="form-control" placeholder="Password"><br> </div> <button type="reset" class="btn btn-default">reprovision</button> <button class="btn btn-primary" >recognize</button> {# </form>#} </div> <script> var b1 = ("b1") $(document).ready(function () { ('click', function () { $.ajax({ url: '', type: 'post', data: ({ 'username': ("username").value, 'password': ("password").value, 'password2': ("password2").value }), contentType: 'application/json', success: function (data) { alert(()) }, error: () => { ('Error') } }) }) }) </script> </body> </html>
# Back-end def register(request): if == 'POST' and request.is_ajax(): # data = data = (()) print(data) username = ('username') password = ('password') print(username, password) # (username=username,password=password) state = {'state': 200} return JsonResponse(state) return render(request, 'app01/')
to this article on the use of Ajax Django environment is introduced to this article , more related to the use of Ajax Django content please search for my previous articles or continue to browse the following related articles I hope that you will support me in the future !