In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains how Jquery uses the AJAX method to request data. Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how Jquery uses the AJAX method to request data.
1. AJAX request 1, jQuery.ajax (url, [settings]):
Load remote data through a HTTP request.
The underlying AJAX implementation of jQuery. For easy-to-use high-level implementations, see $. Get, $. Post, etc. $.ajax () returns the XMLHttpRequest object it created. In most cases, you don't need to manipulate the function directly.
Example: save the data to the server and display the information when it is successful.
$.ajax ({type: "POST", url: "some.php", data: {name: "John", location: "Boston"}}) .done (function (msg) {alert ("Data Saved:" + msg);}); 2. Ajax option
Async (default: true): whether it is an asynchronous request
Global (default: true): whether the global AJAX event is triggered
Url (default: current page address) "address to which the request is sent
Type (default: 'GET'): request method ("POST" or "GET"). If you want to pass Chinese in the parameter Get, you need to use encodeURIComponent ().
Data: data sent to the server. An object or array can be automatically converted to the request string format.
DataType (default: Intelligent Guess (xml, json, script, or html)): the type of data expected to be returned by the server. If not specified, jQuery automatically determines intelligently based on the MIME information of the HTTP package, such as the XML MIME type is recognized as XML.
Context: used to set the context of the Ajax-related callback function. By default, this context is the parameter setting object settings used by an ajax request.
Cache (default: true, default is false when dataType is "script" and "jsonp"): if set to false, the browser will not cache this page.
3. Callback function
If you want to process the data from $.ajax (), you need to use callback functions: beforeSend, error, dataFilter, success, complete.
BeforeSend: called before the request is sent, passing in a XMLHttpRequest as an argument.
Error: called when an error occurs in the request. Pass in a XMLHttpRequest object, a string describing the error type, and an exception object, if any
DataFilter: called after the request is successful. Pass in the returned data and the value of the "dataType" parameter. And the new data (which may be processed) must be returned and passed to the success callback function.
Success: called after the request. Pass in the returned data and a string containing the success code.
Complete: this function is called when the request is complete, regardless of success or failure. Pass in a XMLHttpRequest object and a string containing a success or error code.
4. The difference between GET method and POST method.
Get is to get data from the server, get is to add the parameter data queue to the URL, and the value corresponds to each field in the form, which can be seen in URL. (the server uses Request.QueryString to get the value of the variable)
Post transfers data to the server. Post transmits the parameter data queue to the URL address together in the HTML HEADER through the HTTP post mechanism. The process is not visible to the user. (the server uses Request.Form to obtain the submitted data)
The amount of data transmitted by get is small and cannot be greater than 2KB. Post transmits a large amount of data and is generally regarded as unrestricted by default. But in theory, the maximum amount of IIS4 is 80KB and 100KB in IIS5.
Get security is very low, post security is high, but the execution efficiency is better than Post method. If confidential information is included, it is recommended to submit Post data.
Get is recommended when querying data, while Post is recommended when data is added, modified or deleted.
2. Shortcut method for AJAX request: 1. Load (url [, data] [, callback]):
Load the data from the server and insert the returned HTML code into the matching element.
If the "complete" callback function is provided, it will be called after the function has been processed and the HTML has been inserted.
GET mode is used by default, and POST mode is used if the data parameter provides an object.
For example:
/ / 1. In an ordered list, load the footer navigation of the home page. $("# new-nav"). Load ("/ # jq-footerNavigation li"); / / 2, display a message if the Ajax request encounters an error $("# success"). Load ("/ not-here.php", function (response, status, xhr) {if (status = = "error") {var msg = "Sorry but there was an error:"; $("# error") .html (msg + xhr.status + "" + xhr.statusText);}) / / 3. Send data parameters in array form to the server. $("# objectID"). Load ("test.php", {'choices []': ["Jon", "Susan"]}); / / 4. Load the feeds.html file to DIV.$ ("# feeds"). Load ("feeds.html") where ID is feeds; 2. Get (URL,callback):
Request data from the server through a HTTP GET request.
The following example uses the $.get () method to retrieve data from a file on the server:
("button") .click (function () {$.get ("demo_test.asp", function (data,status) {alert ("Data:" + data + "\ nStatus:" + status);}); 3, $.post (URL,data,callback):
Request data from the server through a HTTP POST request.
The following example uses $.post () to send data along with the request:
("button") .click (function () {$.post ("demo_test_post.asp", {name: "Donald Duck", city: "Duckburg"}, function (data,status) {alert ("Data:" + data + "\ nStatus:" + status);}); 4, $.getJSON (url,data,callback):
Load JSON data through an HTTP GET request.
The data data is appended to the URL of a query string and sent to the server. If the data parameter of the value is a normal object, it is converted to a string and encoded with URL before being appended to the URL.
The following example loads the last four pictures labeled cats from Flickr JSONP API:
GetJSON ("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {tags:" mount rainier ", tagmode:" any ", format:" json "}, function (data) {$.each (data.items, function (iArt item) {$()
") .attr (" src ", item.media.m) .appendto (" # images "); if (I = = 3) return false;});})
Load this JSON data through test.js and use the name value in the returned JSON data:
$.getJSON ("test.js", function (json) {alert ("JSON Data:" + json.users [3] .name);}); 5, $.getScript (url [, callback]):
Use a HTTP GET request to load and execute a JavaScript file from the server
The loaded script executes in the global environment, so you can reference other variables and use the jQuery function. The loaded script also works on the current page.
By default, the $.getScript () cache option is set to false. This appends a timestamp parameter to the query string of the requested URL to ensure that each script downloaded by the browser is re-requested.
We dynamically load the new official jQuery color animation plug-in, which will trigger some color animation once the plug-in is loaded.
(function () {var url = "https://raw.github.com/jquery/jquery-color/master/jquery.color.js";" $.getScript (url, function () {$("# go") .click (function () {$(".block") .animate ({backgroundColor: "rgb (255,180,180)"}, 1000) .delay (1000) .animate ({backgroundColor: "olive"}, 1000)});}); third, global event
Ajax triggers a lot of events.
There are two kinds of events, one is local events and the other is global events:
1. Local events:
Called and allocated through $.ajax.
$.ajax ({beforeSend: function () {/ / Handle the beforeSend event}, complete: function () {/ / Handle the complete event} / /...}); 2. Global event:
You can bind with bind and unbind with unbind.
This is similar to events such as click/mousedown/keyup. But it can be passed on to every DOM element.
$("# loading") .bind ("ajaxSend", function () {/ / use bind $(this). Show ();}) .ajaxComplete (function () {/ / directly use ajaxComplete $(this) .hide ();})
Of course, if one of your Ajax requests does not want to generate global events, you can set global:false
$.ajax ({url: "test.html", global: false,//...})
In global events, except for ajaxStart and ajaxStop, all events have three parameters: event, XMLHttpRequest, and ajaxOptions.
3. Sequence of events
The sequence of events is as follows:
.ajaxStart (global): executes a handler function at the beginning of an AJAX request.
BeforeSend (local event): triggered when an Ajax request starts. If necessary, you can set the XHR object here.
.ajaxSend (global): binds a function to be executed before the Ajax request is sent.
Success (local event): triggered when the request is successful. That is, no error is returned from the server, and there is no error in the returned data.
.ajaxSuccess (global): executes when the Ajax request completes successfully.
Error (local event): triggered only when an error occurs. You cannot execute both success and error callbacks at the same time.
.ajaxError (global): registers a callback handler when an Ajax request goes wrong.
Complete (local event): whether your request succeeds or fails, even if it is a synchronous request, you can trigger this event when the request is completed.
.ajaxComplete (global): register a callback function when the Ajax request is completed.
.ajaxStop (global): executes a handler function when the AJAX request is completed.
For example:
/ / when the AJAX request starts, the indication of "loading" is displayed: $("div") .ajaxStart (function () {$(this) .html ("
");}); / / hiding information after the end of the AJAX request: $(" # loading ") .ajaxStop (function () {$(this). Hide ();}); IV. $ajaxSetup (options):
Sets the global AJAX default options.
For example: set the default address of AJAX request to "/ xmlhttp/", prohibit triggering global AJAX events, and use POST instead of the default GET method. Subsequent AJAX requests no longer set any option parameters
$.ajaxSetup ({url: "/ xmlhttp/", global: false, type: "POST"}); $.ajax ({data: myData}); v. serialize () and .serializeArray ():
Serialize form content
If you want the value of a form element to be included in a sequence string, the element cannot be disabled and must use the name attribute.
1. Serialize ():
Serializes the contents of the form to a string.
The .serialize () method can manipulate jQuery objects that have selected individual form elements, such as, and. However, it is generally easier to choose the tag itself for serialization:
$('form') .submit (function () {alert ($(this) .serialize ()); return false;})
Output standard query string:
A=1&b=2&c=3&d=4&e=52, .serializeArray ():
Serializes the content of the form as an JSON array.
SerializeArray () outputs the standard query JOSN object:
[{name: a value: 1}, {name: B value: 2}, {name: C value: 3}, {name: d value: 4}, {name: e value: 5}] VI. Use Jquery to obtain background code or Webservice
Note: 1. Methods must be static and have a declaration of [WebMethod]
Background:
Using System.Web.Script.Services; [WebMethod] public static string SayHello () {return "Hello Ajax!";}
Front desk:
$(function () {$("# btnOK") .click (function () {$.ajax) ({/ / to use post type: "Post", / / the page where the method is located and the method name url:location.pathname+ "/ SayHello", contentType: "application/json" Charset=utf-8 ", dataType:" json ", success:function (data) {alert (data.d); / / the returned data uses data.d to obtain content}, error:function (err) {alert (err);}}) / / disable the submit return false; of the button});})
Note: if the method needs to pass parameters such as: GetStr (string str,string str2), then $.ajax needs to add data: "{'str':' I am', 'str2':'XXX'}".
7. Read XML data / / 1 through Ajax, parse XML string: var xmlDoc=$.parseXML (""); / / 2, encapsulate XMLDOC:var $xml=$ (xmlDoc) / / 3, determine whether it is XMLDOC:$.isXMLDoc (xmlDoc) = = true//4, query XML, and query HTML syntax: $.xml.find ("title"). Text;$ ("title", $xml). Text ()
Read XML data through Ajax:
$.ajax ({type: "POST", url: "WebService1.asmx/GetDataSet", data: "{}", dataType: 'xml', / / returns the type XML, and the previous Json Success: function (xml) {$(xml) .find ("Table1") .each (function () {$(this) .find ("ID"). Text () + "+ $(this) .children (" title "). Attr (" id ")) });}}); / / if the JOSN text is returned, you need to use $.parstJSON (json) or eval ("(+ json+)") to parse here. I believe you have a better understanding of "how Jquery uses the AJAX method to request data". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.