AJAX(asynchronous JavaScript and XML) is translated into Chinese as " asynchronous JavaScript and xml." Even if you interact asynchronously with the server in Javascript, the data transferred is XML(of course, the data transferred is not just XML).
Search engine automatically prompts for keyword retrieval based on keywords entered by the user.
Another important application scenario is the check-in of the user name at the time of registration.
In fact, these two examples use AJAX technology! When the file box input changes, using AJAX technology to send a request to the server, and then the server will be the results of the query to the browser, and finally the back end to show the results .
<! DOCTYPE html>
The page works as follows:
The urls.py code is as follows:
From django.conf.urls import urlfrom django.contrib import adminfrom app01 Import viewsurlpatterns = [ url (r ' ^admin/') , admin.site.urls), url (r ' ^index/', views.index), url (r ' ^add ', Views.add)
The views.py code is as follows:
From django.shortcuts Import render,httpresponsedef Index (Request): return render (Request, ' index.html ') def add ( Request): n1 = int (Request. Get.get (' N1 ', 0)) n2 = Int (request). Get.get (' N2 ', 0)) he = n1 + n2 return HttpResponse (HE)
$.ajax () parameterThe $.ajax () method is the bottom-most AJAX implementation of jquery. It is structured as:$.ajax (options)
The method has only one parameter, but this object contains information such as the request settings and callback functions required by the $.ajax () method, the parameters are in the form of Key/value, and all parameters are optional. Common parameters are as follows:
1.urlRequires that the requested page be sent as a parameter of type string (default is the current address).
2.typeA parameter of type string is required, and the request method (post or get) defaults to get. Note Other HTTP request methods, such as put and delete, can also be used, but only some browsers support it.
3.timeoutRequires a parameter of type number to set the request time-out (in milliseconds). This setting overrides the global setting of the $.ajaxsetup () method.
4.asyncRequires a parameter of type Boolean, which is set to True by default and all requests are asynchronous requests. If you need to synchronize requests, set this option to false. Note that the synchronization request locks the browser, and the user's other actions must wait for the request to complete before it can be executed.
5.cacheA parameter that is required to be of type Boolean, which defaults to True (False when datatype is a script), false will not load the request information from the browser cache.
6.dataRequires data to be sent to the server as an object or a string of type parameters. If it is not a string, it is automatically converted to a string format. The GET request will be appended to the URL. Prevent this automatic conversion,
You can view the ProcessData option. The object must be in key/value format, for example {foo1: "Bar1", Foo2: "Bar2"} to &foo1=bar1&foo2=bar2. In the case of arrays, jquery automatically corresponds to the same name for different values. For example:
{foo:["bar1", "Bar2"]} is converted to &FOO=BAR1&FOO=BAR2.
7.dataTypeRequires a parameter of type string that expects the data type returned by the server. If not specified, jquery automatically returns Responsexml or ResponseText based on the mine information of the HTTP packet and is passed as a callback function parameter. The following types are available:
XML: Returns an XML document that can be processed with jquery. HTML: Returns plain text HTML information, and the included script tag is executed when the DOM is inserted. Script: Returns plain text JavaScript code. Results are not automatically cached unless the cache parameter is set. Note When you make a remote request (not under the same domain), all post requests are converted to get requests. JSON: Returns the JSON data. Jsonp:json format. When a function is called using the Jsonp form, for example Myurl?callback=?,jquery will automatically replace the latter "?" is the correct function name to execute the callback function. Text: Returns a plain text string.
8.beforeSendParameters that require a function type can modify the functions of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. If you return False in Beforesend, you can cancel this Ajax request. The XMLHttpRequest object is the only parameter.
function (XMLHttpRequest) {this;//The options parameter passed when calling this Ajax request}
9.completeA parameter that is required to be a function type, called after the request has completed (either the request succeeds or the failure is invoked). Parameters: The XMLHttpRequest object and a string that describes the successful request type.
function (xmlhttprequest,textstatus) {this; The options parameter passed when calling this Ajax request}
10.successRequires a parameter of type function, the callback function called after the request succeeds, there are two parameters.
(1) The data returned by the server and processed according to the datatype parameter.
(2) A string describing the status.
function (data,textstatus) {//data may be xmldoc, jsonobj, HTML, text, and so on; The options parameter passed when calling this Ajax request}
11.errorThe function that is called when the request fails with a parameter that is required as a function type. The function has 3 parameters, the XMLHttpRequest object, the error message, and optionally the error object being captured. The Ajax event functions are as follows:
function (Xmlhttprequest,textstatus,errorthrown) {//normally textstatus and Errorthrown only one contains the information this; The options parameter passed when calling this Ajax request}
12.contentTypeA parameter of type string is required when sending information to the server. The content encoding type defaults to "application/x-www-form-urlencoded". This default value is suitable for most applications.
13.dataFilterA function that requires the preprocessing of the original data returned by Ajax, as a parameter of the function type. Provides data and type two parameters. Data is the original data returned by Ajax, and type is the datatype parameter that is provided when Jquery.ajax is called. The value returned by the function will be further processed by jquery.
function (Data,type) {//return data after processing; }
14.globalRequires a parameter of type Boolean, which is true by default. Indicates whether global AJAX events are triggered. Setting to FALSE will not trigger global AJAX events, and Ajaxstart and ajaxstop can be used to control various AJAX events.
15.ifModifiedA parameter of type Boolean is required, and the default is False. Get new data only when the server data changes. Server data changes are based on the last-modified header information. The default value is False, which ignores header information.
16.jsonpRequires a parameter of type string to override the name of the callback function in a JSONP request. This value is used instead of the "callback=?" The "callback" part of the URL parameter in this get or POST request, such as {jsonp: ' onjsonpload ', causes the "onjsonpload=?" passed to the server.
17.usernameA parameter of type string that is required to respond to a user who accesses an authentication request in HTTP.
18.passwordA parameter of type string that is required to respond to the password for HTTP access authentication request.
19.processDataRequires a parameter of type Boolean, which is true by default. By default, the sent data is converted to an object (technically speaking, not a string) to match the default content type "application/x-www-form-urlencoded". Set to False if you want to send DOM tree information or other information that you do not want to convert.
20.scriptCharsetA parameter of type string is required and is used to force the character set (charset) only if the request is datatype as "JSONP" or "script" and the type is get. Typically used when local and remote content encodings are different.
Ajax request How to set Csrf_token mode 1It is sent in data by getting the Csrfmiddlewaretoken value in the hidden input tag.
$.ajax ({ URL: "/cookie_ajax/", Type: "POST", data: { "username": "Q1mi", "password": 123456, "Csrfmiddlewaretoken": $ ("[name = ' Csrfmiddlewaretoken ']"). Val () //Use jquery to remove the value of Csrfmiddlewaretoken, Splicing to Data }, success:function (data) { console.log (data);} })
Mode 2Sent in the request header by getting the string placed in the returned cookie.
Note: A jquery.cookie.js plugin needs to be introduced.
$.ajax ({ URL: "/cookie_ajax/", Type: "POST", headers: {"X-csrftoken": $.cookie (' Csrftoken ')}, // Take csrf_token from the cookie and set the AJAX request header data: {"username": "Q1mi", "Password": 123456}, success:function (data) { Console.log (data);} })
or write a GetCookie method with yourself:
function GetCookie (name) { var cookievalue = null; if (document.cookie && document.cookie!== ") { var cookies = Document.cookie.split (';'); for (var i = 0; i < cookies.length; i++) { var cookie = Jquery.trim (Cookies[i]); Does this cookie, string begin with the name we want? if (cookie.substring (0, name.length + 1) = = = (name + ' = ')) { Cookievalue = decodeuricomponent (cookie.substring (NAME.L Ength + 1)); Break ; }}} return cookievalue;} var csrftoken = GetCookie (' Csrftoken ');
Every time it's so hard to write, you can use the $.ajaxsetup () method to set the AJAX request uniformly.
function Csrfsafemethod (method) { //These HTTP methods does not require CSRF protection return (/^ (get| head| options| TRACE) $/.test (method));} $.ajaxsetup ({ beforesend:function (XHR, settings) { if (!csrfsafemethod (settings.type) &&!) This.crossdomain) { xhr.setrequestheader ("X-csrftoken", Csrftoken);}} );
For more details, see the Djagno official documentation for CSRF content
Ajax User Manual