Python full stack development Road "18th": Ajax technology

Source: Internet
Author: User
Tags script tag browser cache

Ajax Technology

Ajax = asynchronous JavaScript and XML.

Ajax is a technique that can update parts of a Web page without reloading the entire page.

1. The load () method of jquery

The JQuery load () method is a simple but powerful Ajax method.

The load () method loads the data from the server and puts the returned data into the selected element.

Grammar:

$ ("selector"). Load (url,data,callback);
1, the required URL parameter specifies the URL address 2, the optional data parameter specifies the query string key/value pairs sent together with the request set 3, the optional callback parameter is the function name that is executed after the load () method completes

First case

$ (' #btn '). Click (function () {    //pass only one URL, indicating that the element with ID #new-projects is loaded index.html    $ (' #new-projects '). Load ('./ Index.html ');})

The second case

$ (' #btn '). Click (function () {    //pass only one URL, the imported index.html file contains multiple pass parameters, similar to: Index/html?name= ' Zhang San '    $ (' # New-projects '). Load ('./index.html ', {"name": ' Zhang San ', "Age": 12});})

The third case

After loading the file, there will be a callback function that indicates the loaded function    $ (' #new-projects '). Load ('./index.html ', {"name": ' Zhang San ', "Age": 12},function () {});

注意:load函数最好在服务器网页中应用,也就是说要在服务器上运行,本地调试需要搭建后端本地环境。

2, the Getjson method of jquery

jquery uses the Getjson () method to asynchronously load JSON-formatted data in Ajax. Get data from the server and parse the data to display it in the page

Syntax: $.getjson (Url,[data],[callback])

url参数为请求加载json格式文件的服务器地址,可选项data参数为请求时发送的数据,callback参数为数据请求成功后执行的函数。

$.getjson ("./data/getjson.json", function (data) {       var str = "";//Initialize the Save content variable       $.each (data, function (index, Ele) {          $ (' ul '). Append ("<li>" +ele.name+ "</li  (>")          });       })
3. jquery's $.get () method

The $.get () method requests data from the server over an HTTP GET request

Syntax: $.get (URL, callback);

url参数规定你请求的路径,是必需参数,callback参数为数据请求成功后执行的函数。

$.get ('./data/getjson.json ', function (data,status) {    console.log (status);   Success    200 status code OK              })
4. The post () method of jquery

Compared to the Get () method, the post () method is used to send data to the server in post, the server receives the data, processes it, and returns the processing result to the page

Syntax: $.post (url,data,callback);

url参数规定你请求的路径,是必需参数,可选的data参数是连同请求发送的数据。可选的callback参数为数据请求成功后执行的函数。

$.post ('/index ', {name: ' Zhang San '},function (data,status) {      console.log (status);})
5. jquery's $.ajax () method

jquery的$.ajax()方法 是做ajax技术经常使用的一个方法。

它的参数很多,总会有一些初学者记不住,在这里,演示几个经常使用的参数。后面讲django课程的时候老师会详细讲ajax技术的原理。大家先把每个参数做个笔记。

the parameters are as follows: 1.url: A parameter of type string is required, (default is the current page address) to send the requested address. 2.type: A 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.timeout: Requires a parameter of type number to set the request time-out (in milliseconds). This setting overrides the global setting of the $.ajaxsetup () method. 4.async: Requires a parameter of type Boolean, which is set to True by default and all requests are asynchronous requests. If you need to send a synchronization request, 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.cache: A parameter that is required to be of type Boolean, which defaults to True (False when datatype is a script), and set to false will not load the request information from the browser cache. 6.data: Data sent to the server is required for an object or string type parameter. If it is not already a string, it is automatically converted to a string format. The GET request will be appended to the URL. To prevent this automatic conversion, you can view the ProcessData option. The object must be in key/value format, for example {foo1: "Bar1", Foo2: "Bar2"} into&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.dataType: A parameter of type string is required that expects the data type returned by the server. If not specified, jquery automatically returns Responsexml or ResponseText based on the HTTP packet mime information and is passed as a callback function parameter. The available types are: 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:JSONP format. When a function is called using the Sonp 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.beforeSend: Functions that require a function type, such as adding custom HTTP headers, can be modified before sending a request to a XMLHttpRequest object. 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 that is passed when calling this Ajax request} 9.complete: A parameter that is required to be a function type, called when the request is complete (invoked when the request succeeds or fails). Parameters: The XMLHttpRequest object and a string that describes the successful request type. function (XMLHttpRequest, textstatus) {this;//The options parameter that is passed when calling this Ajax request}10.success: A parameter that requires a function type, a callback function that is 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 this;//The options parameter passed when calling this Ajax request}11.error: The function that is called when the request fails with a parameter that is required as a function type. The function has 3 parameters, that is, the XMLHttpRequest object, the error message, the caught errorImage (optional). The Ajax event functions are as follows: function (XMLHttpRequest, textstatus, Errorthrown) {//normally textstatus and Errorthrown only one contains information this; The options parameter passed when calling this Ajax request}12.contenttype: A parameter of type string that, when sent to the server, defaults to "application/x-www-form-urlencoded" for the content encoding type. This default value is suitable for most applications. 13.dataFilter: A function that requires a parameter of type function to preprocess the original data returned by Ajax. 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) {//returns data returned after processing;} 14.dataFilter: A function that requires a parameter of type function to preprocess the original data returned by Ajax. 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) {//returns data returned after processing;} 15.global: A parameter of type Boolean is required and is true by default. Indicates whether global AJAX events are triggered. Setting to FALSE will not trigger global AJAX events, Ajaxstart or ajaxstop can be used to control various AJAX events. 16.ifModified: A 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. 17.JSONP: Requires a parameter of type string, overriding 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. 18.username: A parameter of type string is required forThe user name that responds to HTTP access authentication requests. 19.password: A parameter of type string is required to respond to the password for HTTP access authentication request. 20.processData: A parameter of type Boolean is required and is true by default. By default, the data sent is converted to an object (technically 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. 21.scriptCharset: A 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.
Get () mode  $.ajax ({     URL: './data/index.txt ',     type: ' Get ',     dataType: ' text ',     success:function ( Data) {        $ (' P '). HTML (data);     },     error:function (Error) {        Console.log (error)     }
Post () mode $.ajax ({   URL: '/index ',   type: ' Post ',   data:{name: ' Zhang San ', age:12},   success:function ( Data) {      $ (' P '). HTML (data);   },   error:function (Error) {      Console.log (Error)}
6. XMLHttpRequest Object

The core of Ajax technology is the XMLHttpRequest object. This object acts as an intermediary between the script in the browser and the server. However, different browsers implement XMLHttpRequest objects differently. To ensure cross-browser, you have to write different code branches for the same thing for the same thing.

In the following example, save as ajax.html:

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <Metaname= "Viewport"content= "Width=device-width, User-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">    <Metahttp-equiv= "X-ua-compatible"content= "Ie=edge">    <title>Ajax</title></Head><Body>    <DivID= "new"></Div>        <Scriptsrc= "Scripts/addloadevent.js"></Script>    <Scriptsrc= "Scripts/gethttpobject.js"></Script>    <Scriptsrc= "Scripts/getnewcontent.js"></Script></Body></HTML>

To create a new object in IE, use the following code:

var request = new ActiveXObject ("msxml2.xmlhttp.3.0");

Other browsers create new objects based on XMLHttpRequest:

var request = new  XMLHttpRequest ();

Even more troubling is that the XMLHTTP objects used in different versions of IE are not exactly the same. In order to be compatible with all browsers,the Gethttpobject function in the Gethttpobject.js file is written like this:

function Gethttpobject () {    if (typeof XMLHttpRequest = = = = "undefined")        XMLHttpRequest = function () {            try {RET Urn new ActiveXObject ("msxxml2.xmlhttp.6.0");}                catch (e) {}            try {return new ActiveXObject ("msxxml2.xmlhttp.3.0");}                catch (e) {}            try {return new ActiveXObject ("Msxxml2.xmlhttp");}                catch (e) {}            return false;        }        return new XMLHttpRequest ();}

Gethttpobject detects XMLHttpRequest by object detection technology. If it fails, it continues to detect other methods and eventually returns false or a new XMLHttpRequest object.

This allows the new object to be assigned directly to a variable:

var request = Gethttpobject ();

Python full stack development Road "18th": Ajax technology

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.