71. django Ajax continued, 71. djangoajax
Next, I wrote the article. Continue to introduce the use of ajax.
Last friendship: http://www.cnblogs.com/liluning/p/7831169.html
Navigate to this article:
- Ajax response parameters
- Csrf Cross-Site Request Forgery
- JQuery. serialize ()
- Upload files
I. Ajax response parameters
At the end of the previous article, I introduced the ajax Request Parameters and now added a response parameter.
DataType: The expected type of data returned by the server. The data returned by the server is parsed based on this value and passed to the callback function. By default, you do not need to explicitly specify this attribute. ajax will convert the content Type returned by the server. For example, the content Type returned by our server is in json format, in this case, the ajax method converts the response content in json format. if the conversion is successful, we will get an object in json format in the success callback function; if the conversion fails, the error callback function is triggered. If we explicitly specify the target Type, we can use data Type. Available value of dataType: html | xml | json | text | script
Simply put, it tells the server what data type to return.
Ii. csrf Cross-Site Request Forgery
When we used form POST for submission, if the client does not receive {% csrf_token %}, the client will report an error. Likewise, ajax POST will submit data with the same error. Is this correct?
1. method 1
$.ajaxSetup({ data: {csrfmiddlewaretoken: '{{ csrf_token }}' },});$.ajax({ ... })
Disadvantage: When JavaScript and html files are separated, {csrf_token} cannot be rendered out of service. method 1 must write JavaScript and html together.
2. method 2
{% csrf_token %}$.ajax({ url:"", type:"POST", data:{ csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val(), }})
Disadvantage: the html body tag must contain {% csrf_token %}
3. Method 3
// <Script src = "{% static 'js/jquery. cookie. js '%} "> </script> need to download the corresponding file <script src =" https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js "> </script> $. ajax ({headers: {"X-CSRFToken": $. cookie ('csrftoken ')},})
Disadvantage: basic common hahaha
Iii. jQuery. serialize ()
serialize()
Function usedSerializes a set of form elements and encodes the form content into a string for submission..serialize()
Functions are often used to serialize form content for AJAX submission. This function is mainly based onUsed for submissionOfValidThe name and value of the Form Control that concatenates them into a text string that can be directly used for form submission that has passed standard URL encoding (character set encoding for UTF-8 ). This function does not serialize form controls that do not need to be submitted, which is consistent with the regular form submission behavior. For example: form controls that are not in the <form> label are not submitted, form controls without the name attribute are not submitted, form controls with the disabled attribute are not submitted, and unselected form controls are not submitted.
Summary: if we have a lot of input TAG content that needs to be submitted, it will not be listed in data. This is used.serialize()
The function can help us submit data to the client at one time.
For example:
<Form name = "myForm" action = "http://www.365mini.com" method = "post"> <input name = "uid" type = "hidden" value = "1"/> <input name = "username" type = "text" value = "Zhang San"/> <input name = "password" type = "text" value = "123456"/> <select name =" grade "id =" grade "> <option value =" 1 "> grade 1 </option> <option value =" 2 "> grade 2 </option> <option value =" 3 "selected =" selected "> grade 3 </option> <option value =" 4 "> grade 4 </option> <option value =" 5 "> grade 5 </option> <option value = "6"> Sixth Grade </option> </select> <input name = "sex" type = "radio" checked = "checked" value = "1"/> male <input name = "sex" type = "radio" value = "0"/> female <input name = "Hober" type = "checkbox" checked = "checked" value = "1"/> swimming <input name = "holobby" type = "checkbox" checked = "checked" value = "2"/> running <input name = "holobby" type = "checkbox" value = "3"/> badminton <input name = "btn" id = "btn" type = "button" value = "click"/> </form>
Submit data
Serializing <form> elements can directly serialize all form elements in the <form> element.
Serialize all: $ ("form"). serialize ()
uid=1&username=%E5%BC%A0%E4%B8%89&password=123456&grade=3&sex=1&hobby=1&hobby=2
Partial serialization: $ (": text, select,: checkbox"). serialize ()
username=%E5%BC%A0%E4%B8%89&password=123456&grade=3&hobby=1&hobby=2
How does a view function take values? Same as previous POST requests
Request. POST. get ("name") // name attribute in input
Iv. upload files
1. Normal File Upload
1) template
<Form action = "/upload/" method = "post" enctype = "multipart/form-data" >{% csrf_token %} <p> User Name <input type = "text" name = "user"> </p> <p> profile picture <input type = "file" name = "avatar"> </p> <input type = "submit"> </form>
The enctype attribute is indispensable.
2) view
Def upload (request): if request. method = "POST": print ("POST", request. POST) print ("FILES", request. FILES) # FILES <MultiValueDict :{}> file_obj = request. FILES. get ("avatar") print (file_obj.name, "-----") with open (file_obj.name, "wb") as f: for I in file_obj: f. write (I) return HttpResponse ("succeeded") return render (request, "upload.html ")
This is the name Method for writing the uploaded file to the local file_obj. You can obtain the file name.
3. Ajax (FormData)
XMLHttpRequest Level 2 adds a new interfaceFormData
. ExploitationFormData object
We can use JavaScript to simulate a series of Form Controls with some key-value pairs. We can also use the XMLHttpRequestsend()
Method To asynchronously submit this form.FormData
The biggest advantage is that we can upload a binary file asynchronously.
1) template
<Body> <form action = "" id = "s1"> <p> name <input type = "text"> </p> <p> password <input type =" password "> </p> <p> profile picture <input type =" file "id =" upload_avatar "> </p> </form> <p> <button class =" ajax_send "> submit </button> <span class =" login_error "> </span> </p> <script src =" https://cdn.bootcss.com/jquery/3.2.1/jquery.js "> </script> <script src = "https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"> </script> <script> function foo () {$ (". Login_error "pai.html (" ")} $ (". ajax_send "). click (function () {var formData = new FormData (); formData. append ("username", $ (": text "). val (); formData. append ("password", $ (": password "). val (); formData. append ("avatar", $ ("# upload_avatar") [0]. files [0]); $. ajax ({url: "/get_ajax/", type: "POST", headers: {"X-CSRFToken": $. cookie ('csrftoken')}, data: formData, contentType: false, processData: false, success: Function (data) {var data = JSON. parse (data); if (! Data ["flag"]) {$ (". login_error ").html (" Incorrect username or password ") setTimeout (foo, 3000) }}) </script> </body>
View Code
2) view
def get_ajax(request): username=request.POST.get("username") password=request.POST.get("password") print("FIFLE",request.FILES) print("POST",request.POST) response={"flag":False} if username=="bjd" and password=="123": response["flag"]=True import json return HttpResponse(json.dumps(response))