Get an ajax note for easy query-$. ajax (), ajax. ajax

Source: Internet
Author: User
Tags http authentication

Get an ajax note for easy query-$. ajax (), ajax. ajax

$. Ajax () is the underlying method in all ajax methods. All other methods are encapsulated based on the $. ajax () method.
This method has only one parameter, passing an object of each function key-value pair.

$. Ajax () method object parameter table:

Parameter type description: The url String sending request address type String Request Method: POST or GET. By default, GETtimeout Number sets the request timeout time (in milliseconds) data Object or String sent to the server, the data type returned by the object or key-Value Pair String dataType String, for example, before a beforeSend Function such as html, xml, or json sends a request, you can modify the Function of the XMLHttpRequest object. After the complete Function request is complete, the called callback Function seccess Function fails to be called. the global Boolean callback function called by the time is true by default, indicates whether to trigger global Ajaxcache Boolean to set browser cache response. The default value is true. If the dataType type is script or jsonp, the value is false. Content DOM specifies an element as the context of all callback functions related to the request. ContentType String specifies the type of the request content. The default value is application/x-www-form-urlencoded. Async Boolean asynchronous processing. The default value is true. false indicates that processData Boolean for synchronous processing is true by default, and data is processed in URL encoding format. If this parameter is set to false, the imported data is not processed in the URL encoding format. The callback Function used to filter response data. The default value of ifModified Boolean is false. header detection is not performed. If this parameter is set to true, header detection is performed. When the content of the request changes from the previous request, the request is considered successful. Jsonp String specifies a query parameter name to overwrite the default jsonp callback parameter name callback. Username String username used in the HTTP authentication request password String the password scriptCharset String used in the HTTP authentication request when the remote and local content use different character sets, used to set the character set used by the script and jsonp requests. The xhr Function is used to provide the custom callback Function traditional Boolean implemented by XHR instances. The default value is false, and parameter serialization in the traditional style is not used. If it is true, it is used.
$('.ajax_btn').on('click',function(){    $.ajax({        type:"GET",        url:"ajax.php",        data:{            url:"snail",        },        success:function(response,status,xhr){            console.log(response);        }    })});

Note: For data attributes, if the GET mode is used, three methods can be used. For POST mode, you can use the previous two forms.

I. Loading requests when Ajax sends requests asynchronously, the request time may be long if the network speed is slow. If the request exceeds a certain period of time, the user will no longer be bored and close the page. If you can give users some prompts during the request, such as: loading..., the same request time will make the user experience better.
Query provides two global events:. ajaxStart () and. ajaxStop (). The two global events are activated when the user triggers Ajax and the request starts (other requests are not completed. ajaxStart () is activated when the request ends (all requests are completed. ajaxStop ().
$('.ajax_load').ajaxStart(function(){    $(this).show();}).ajaxStop(function(){    $(this).hide();});

Note: The above code is not valid in jQuery1.8 or later versions. You must use jquery-migrate for backward compatibility to run the code. The new version must be bound to the document element.

$(document).ajaxStart(function(){    $('.ajax_load').show();}).ajaxStop(function(){    $('.ajax_load').hide();});
// The page is suspended due to a long request time. Therefore, you can set the timeout value $. ajax ({timeout: 2000 ,});
// If ajax does not want to trigger a global event, you can set cancellation, for example, canceling triggering. ajaxStart () and. ajaxStop () Global Event: $. ajax ({global: false ,});
Ii. When Ajax is asynchronously submitted for error processing, it is impossible to complete all the tasks successfully, and the submission fails due to code asynchronous file errors and network errors. In this case, we should report the error and remind the user to resubmit or notify the developer to fix it. In the previous high-level encapsulation, there was no callback error processing, such as $. get (), $. post (), and. load (). Therefore, early methods use the global. ajaxError () event Method to return error messages. After jQuery1.5, you can use the local. error () method through concatenation. For the $. ajax () method, you can not only use these two methods, but also use its own attribute method error: function (){}.
$('.ajax_btn').on('click',function(){    $.ajax({        type:"GET",        url:"ajax.php",        data:{            url:"snail",        },        success:function(response,status,xhr){            console.log(response);        },        error:function(xhr,errorText,errorStatus){            console.log(xhr);            console.log(errorText);            console.log(errorStatus);        }    })});
// $. Post () uses concatenation. the error () method indicates an error. The concatenation method will be. fail () Replace $. post ('ajax. php '). error (function (xhr, status, info) {console. log (xhr. status + ':' + xhr. statusText); console. log (status + ':' + info );});
// $. Post () uses global. ajaxError () event prompt error $ (document ). ajaxError (function (event, xhr, settings, infoError) {alert (xhr. status + ':' + xhr. statusText); alert (settings + ':' + info );});
Iii. Request for global events jQuery provides many global event methods for Ajax operations, such as. ajaxStart (),. ajaxStop (),. ajaxError () and so on. They all belong to global events triggered during the request. In addition to these, there are some other global events :. ajaxSend (). There is no corresponding local method. Only the beforeSend attribute is available. The function to be bound before the request is sent .. AjaxComplete () corresponds to a local method:. complete (). After the request is complete, register a callback function .. AjaxSuccess () corresponds to a local method:. success (), which is executed when the request is successful. Note: The global event method is triggered by all Ajax requests and can only be bound to the document. The local method is for a specific Ajax. Most of the parameters of some global event methods are objects. You can obtain the attributes or methods of these objects by traversing them.
// Traverse the properties of the settings object $ (document ). ajaxSuccess (function (event, xhr, settings) {for (var I in settings) {console. log (I );}});
// $. Post () local method of request Completion. complete () $. post (). complete (function (xhr, status) {console. log ("finished! ");})
// $. Post () Global Method of request Completion. ajaxComplete () $ (document). ajaxComplete (function (event, xhr, setting) {console. log ("completed! ");})
// $. Ajax () method, which can be directly set through attributes. $. Ajax ({type: "POST", url: "ajax. php ", success: function (data, status, xhr) {}, complete: function (xhr, status) {}, beforeSend: function (xhr, settints ){}})

Note: After jQuery1.5, use. success (),. error () and. the complete () concatenation method can be used. done (),. fail () and. replace always.

4. If JSON and JSONP are in the same domain, the $. ajax () method can load the JSON file by setting the dataType attribute. In a non-same domain, JSONP can be used, but it is also conditional. To operate files across domains, we must use JSONP. JSONP (JSON with Padding) is an unofficial protocol that allows the server to integrate Script tags to return to the client, cross-origin access is implemented through javascriptcallback (this is only a simple implementation form of JSONP ).
$.ajax({    type:"GET",    dataType:"jsonp",    success:function(data,status,xhr){}})
5. Before jqXHR objects, we used local methods:. success (),. complete (), and. error (). These three local methods are not called by the XMLHttpRequest object, but are called by the objects returned by global methods such as $. ajax. This object is a jqXHR object, which is a superset of the native object XHR. Note: If the jqXHR object is used, we recommend that you use it. done (),. always () and. fail () replacement. success (),. complete () and. error (). In future versions, the three methods may be removed. Use jqXHR connection mode ratio $. the attributes of ajax () have three advantages: 1. it can be joined to improve readability. 2. the same callback function can be executed multiple times. 3. specify the callback function for multiple operations;

 

Related Article

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.