jQuery ajax learning

jQuery is a very common JavaScript library, but I suddenly found that most of the time, I actually turn a blind eye to it subconsciously. For example, its ajax, it is not unused, every time I use it, or I directly apply the existing one. The format, or copy it directly from the official website and then modify it, has never been studied in depth. It didn't say that I remembered it clearly in my chest. This time, since I realized it, I took the time to understand it thoroughly. Although a framework may be outdated, the things he uses, the ideas, will always make you gain something in the learning process. In addition, if you know one thing, you won't give yourself unnecessary fear and pressure because of the unfamiliarity when you encounter it, o(* ̄︶ ̄*)o.

One, what is jQuery ajax?

With jQuery AJAX methods, HTTP Get and HTTP Post can be used to request text, HTML, XML or JSON from a remote server - and you can load this external data directly into selected elements of a web page. This sentence contains many elements: First, jQuery ajax can use the get method and the post method. Second, it can request text, it can request html, it can request xml, and it can request data in json format.

$(document).ready(function(){
  $("#b01").click(function(){
  htmlobj=$.ajax({url:"/jquery/test1.txt",async:false});
  $("#myDiv").html(htmlobj.responseText);
  });
});

Second, what methods are included in jQuery ajax

1.jQuery load() 

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

 grammar:

$(selector).load(URL,data,callback);

2.$.get()

Syntax: $.get( URL , callback );

$("button").click(function(){
  $.get("demo_test.asp",function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});

3.$.post() 

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

$("button").click(function(){
  $.post("demo_test_post.asp",
  {
    name:"Donald Duck",
    city:"Duckburg"
  },
  function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});

4.jQuery.ajax(url,[settings])

Load remote data via HTTP request. url: A string containing the URL to send the request to. settings: AJAX request settings. All options are optional.

Callback

If you want to process the data obtained by $.ajax(), you need to use a callback function. beforeSend, error, dataFilter, success, complete. Among these functions, the most commonly used is the success function, and the others are rarely used. The commonly used ones are given first, and all related settings items will be listed later.

  • beforeSend is called before sending the request, and passes an XMLHttpRequest as a parameter.
  • error is called when an error occurs in the request. Pass in the XMLHttpRequest object, a string describing the type of error, and an exception object (if any)
  • dataFilter is called after a successful request. Pass in the returned data and the value of the "dataType" parameter. And must return new data (possibly processed) to pass to the success callback function.
  • success is called after the request. Pass in the returned data, and a string containing the success code.
  • complete This function is called when the request has completed, whether it succeeded or failed. Pass in the XMLHttpRequest object, and a string containing a success or error code.

settings item:

accepts: Default: Depends on data type. Content-Type sends request headers to tell the server what kind of responses to return. If the accepts setting needs to be modified, it is recommended to do it once in the $.ajaxSetup() method.

async: (default: true) By default, all requests are asynchronous. Set this option to false if you need to send synchronous requests. Note that synchronous requests will lock the browser, and other user operations must wait for the request to complete before they can be performed.

beforeSend(XHR): A function that can modify the XMLHttpRequest object before sending a request, such as adding custom HTTP headers. The XMLHttpRequest object is the only parameter. This is an  Ajax event . If false is returned, the ajax request can be cancelled.

cache: (default: true, default is false when dataType is script and jsonp) New in jQuery 1.2, set to false will not cache this page.

complete(XHR, TS): The callback function after the request is completed (called after the request succeeds or fails). Parameters: XMLHttpRequest object and a string describing the type of successful request. Ajax events .

contents: An object paired with "{string:regex}" that determines how jQuery will parse the response, given its content type.

contentType: (default: "application/x-www-form-urlencoded") The content encoding type when sending information to the server. The default value is suitable for most situations. If you explicitly pass a content-type to $.ajax() then it must be sent to the server (even if there is no data to send)

context: This object is used to set the context of Ajax related callback functions. That is to say, let this in the callback function point to this object (if this parameter is not set, then this points to the options parameter passed when calling this AJAX request). For example, specifying a DOM element as the context parameter sets the context of the success callback function to this DOM element. like this:

converters: default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML}, an object of datatype to datatype converters . The value of each transformer is a function that returns the transformed value of the response

crossDomain: Default: false for same-domain requests, true for cross-domain requests If you want to force cross-domain requests (such as JSONP) to be in the same domain, set crossDomain to true. This makes, for example, a server-side redirect to another domain

data: The data sent to the server. will be automatically converted to request string format. It will be appended to the URL in GET requests. See the processData option description to disable this automatic conversion. Must be in Key/Value format. If it is an array, jQuery will automatically assign different values ​​to the same name. For example, {foo:["bar1", "bar2"]} is converted to "&foo=bar1&foo=bar2".

dataFilter: A function for preprocessing the raw data returned by Ajax. Provide two parameters data and type: data is the original data returned by Ajax, and type is the dataType parameter provided when calling jQuery.ajax. The value returned by the function will be further processed by jQuery.

dataType:

The expected data type returned by the server. If not specified, jQuery will automatically make intelligent judgments based on HTTP packet MIME information, such as XML MIME type is recognized as XML. In 1.4, JSON will generate a JavaScript object, and script will execute the script. Then the data returned by the server will be parsed according to this value and passed to the callback function. Available values:

"xml": Returns an XML document, which can be processed with jQuery.

"html": Returns plain text HTML information; included script tags are executed when inserted into the dom.

"script": Returns plain text JavaScript code. Results are not automatically cached. Unless the "cache" parameter is set. '''Note:'''When making remote requests (not under the same domain), all POST requests will be converted to GET requests. (because it will be loaded using the DOM's script tag)

"json": Returns JSON data.

"jsonp":  JSONP  format. When calling a function using the  JSONP  form, such as "myurl?callback=?" jQuery will automatically replace the ? with the correct function name to execute the callback function.

"text": returns a plain text string

error: (default: automatic judgment (xml or html)) This function is called when the request fails. There are three parameters: XMLHttpRequest object, error message, (optional) caught exception object. If an error occurs, the error message (second parameter) may be "timeout", "error", "notmodified" and "parsererror" in addition to null.

global: (default: true) whether to trigger global AJAX events. Set to false will not trigger global AJAX events such as ajaxStart or ajaxStop which can be used to control different  Ajax events .

headers: Default: {}, an additional "{key:value}" pair is mapped to send along with the request. This setting is set before the beforeSend function is called; therefore, the value set in the message header can override any setting within the scope of the beforeSend function.

ifModified: (Default: false) Get new data only when server data changes. Use the HTTP packet Last-Modified header information to determine. In jQuery 1.4, it also checks the server-specified 'etag' to make sure the data has not been modified.

isLocal: Default: depends on the current location protocol. Allows the current environment to be considered "local", (like the filesystem), even though jQuery won't recognize it by default. The following protocols are currently recognized as native: file, *-extension, and widget. If the isLocal setting needs to be modified, it is recommended to do so once in the $.ajaxSetup() method.

jsonp: The name of the callback function to override in a jsonp request. This value is used in place of the "callback" part of the URL parameter in a GET or POST request such as "callback=?", e.g. {jsonp:'onJsonPLoad'} will cause "onJsonPLoad=?" to be passed to the server.

jsonpCallback : Specify a callback function name for the jsonp request. This value will be used in place of the random function name automatically generated by jQuery. This is mainly used to let jQuery generate unique function names, which makes it easier to manage requests, and also provides convenient callback functions and error handling. You can also specify this callback function name when you want the browser to cache GET requests.

mimeType: A mime type used to override the XHR MIME type.

password: the password used to respond to HTTP access authentication requests

processData: (default: true) By default, the data passed in through the data option, if it is an object (technically speaking, as long as it is not a string), will be processed and converted into a query 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 don't want to convert.

scriptCharset: Only when the dataType is "jsonp" or "script" and the type is "GET" will it be used to force the modification of the charset when the request is made. Usually only used when the local and remote content encodings are different.

statusCode: Default: {}, a set of numeric HTTP codes and function objects that call the corresponding code when responding. For example, if the response status is 404, the following alert will be triggered:

success(data, textStatus, jqXHR): The callback function after the request is successful. Parameters: The data returned by the server and processed according to the dataType parameter; a string describing the status. There is also the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success set can accept an array of functions. Each function will be called in turn. Ajax events .

traditional: Set to true if you want to serialize data in the traditional way. Please refer to the jQuery.param method under the Tools category.

timeout: Set the request timeout (in milliseconds). This setting will override the global setting.

type: (default: "GET") Request method ("POST" or "GET"), default is "GET". Note: Other HTTP request methods such as PUT and DELETE can also be used, but are only supported by some browsers.

url: (default: current page address) URL to send the request to.

username: The username used to respond to HTTP access authentication requests

xhr: Need to return an XMLHttpRequest object. The default is ActiveXObject in IE and XMLHttpRequest in other cases. Used to override or provide an enhanced XMLHttpRequest object. This parameter was not available before jQuery 1.3.

xhrFields: A pair of "filename-filevalue" sets XHR objects natively. For example, you can use it for cross-origin requests with withCredentials set to true if desired.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325073736&siteId=291194637