Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the functions in ajax

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, the editor will share with you the relevant knowledge points about what functions are in ajax. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Ajax functions are: 1, "$(selector). Load ()", used to load remote data into the selected element; 2, "$.ajax ()"; 3, "$.get ()"; 4, "$.post ()"; 5, "$.getJSON ()"; 6, "$.getScript ()".

The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.

AJAX request function

Request description $(selector) .load (url,data,callback) load remote data into selected element $.ajax (options) load remote data into XMLHttpRequest object $.get (url,data,callback,type) use HTTP GET to load remote data $.post (url,data,callback,type) use HTTP POST to load remote data $.getJSON (url,data,callback) use HTTP GET to load remote JSON data $.getscript (url) Callback) load and execute remote JavaScript files

(url) URL (address) of the loaded data

(data) the key / value object of data sent to the server

(callback) the function executed when the data is loaded

(type) the type of data returned (html,xml,json,jasonp,script,text)

(options) all key / value pair options for a complete AJAX request

One, $.get (url, [data], [callback])

Description: url is the request address, data is the list of request data, and callback is the callback function after the request is successful. This function accepts two parameters, the first is the data returned by the server, and the second parameter is the status of the server, which is optional.

Among them, the format of the data returned by the server is actually a string situation, not the json data format we want. The reference here is just for comparison.

$.get ("data.php", $("# firstName.val ()"), function (data) {$("# getResponse") .html (data); the data returned by} / / is of string type)

Two, $.post (url, [data], [callback], [type])

Note: this function is similar to the $.get () parameter, with an extra type parameter. Type is the data type of the request and can be html,xml,json and other types. If we set this parameter to: json, then the returned format is in json format. If it is not set, it is the same as the format returned by $.get (), which is a string.

Post ("data.php", $("# firstName.val ()"), function (data) {$("# postResponse") .html (data.name);}, "json" / / sets the type of data to be obtained, so the resulting data is formatted as json)

Three, $.ajax (opiton)

Note: $.ajax () this function is powerful and can accurately control ajax. Please refer to the relevant information if you need detailed instructions.

$.ajax ({url: "ajax/ajax_selectPicType.aspx", data: {Full: "fu"}, type: "POST", dataType:'json',success:CallBack,error:function (er) {BackErr (er);}})

IV, $.getJSON (url, [data], [callback])

$.getJSON ("data.php", $("# firstName.val ()"), function (jsonData) {$("# getJSONResponse") .html (jsonData.id);} / / without setting, the data type obtained directly is json, so you need to use jsonData.id method when calling)

There are more and more AJAX-based applications in When Ajax meets jQuery, and it is not pleasant for foreground developers to deal directly with the underlying HTTPRequest. Since jQuery encapsulates JavaScript, it must have considered the problem of AJAX application. Indeed, it is more convenient to write AJAX in jQuery than to write directly in JS. I don't know if I will lose my knowledge of jQuery if I use JS for a long time. ) assuming that you are already familiar with jQuery syntax, let's summarize some of the applications of ajax.

Load a static page

Load (url, [data], [callback])

The URL address of the HTML page requested by url (String)

Data (Map) (optional parameter) key/value data sent to the server

Callback (Callback) (optional parameter) callback function when the request is completed (does not need to be success)

The load () method makes it easy to load static page content into a specified jQuery object.

$('# ajax-p'). Load ('data.html')

In this way, the contents of the data.html will be loaded into the DOM object whose ID is ajax-p. You can even implement Ajax operations that load part of the content by setting ID, such as:

$('# ajax-p'). Load ('data.html#my-section')

Implement GET and POST methods

Get (url, [data], [callback])

Url (String) sends the URL address of the request.

Data (Map) (optional parameter) the data to be sent to the server, expressed as a key-value pair of Key/value, will be appended to the request URL as QueryString

Callback function when callback (Callback) (optional parameter) is loaded successfully (this method is called only if the return status of Response is success)

Obviously, this is a function designed to implement GET, and it is quite easy to use.

Get ('login.php', {id:' Robin', password: '123456, gate:' index'}, function (data, status) {/ / data is the returned object, and status is the request status alert (data); / / assume that the server script returns the text "Hello, Robin!" Then the browser will pop up a dialog box showing the text alert (status); / / the result will be success, error, etc., but here is the function that can only be run on success); post (url, [data], [callback], [type])

Url (String) sends the URL address of the request.

Data (Map) (optional parameter) the data to be sent to the server, in the form of key-value pairs of Key/value

Callback function when callback (Callback) (optional parameter) is loaded successfully (this method is called only if the return status of Response is success)

Type (String) (optional parameter) Type of request data, xml,text,json, etc.

Is also a simple function provided by jQuery, and its practical usage

$.post ('regsiter.php', {id:'Robin', password:' 123456, type:'user'}, function (data, status) {alert (data);}, "json")

Event-driven script loading function: getScript ()

GetScript (url, [callback])

Url (String) address of the JS file to be loaded

Callback (Function) (optional) callback function after successful loading

The getScript () function can be remotely loaded into a JavaScript script and executed. This function can load JS files across domains (magic...?! ). The significance of this function is huge, it can greatly reduce the amount of code that the page loads for the first time, because you can load the corresponding JS file according to the user's interaction, rather than loading it all at the time of page initialization.

$.getScript ('ajaxEvent.js', function () {alert ("Scripts Loaded!"); / / loads ajaxEvent.js and displays a dialog prompt after successful loading. });

Building a bridge for data communication: getJSON ()

GetJSON (url, [data], [callback])

Url (String) send request address

Data (Map) (optional) Key/value parameters to be sent

Callback (Function) (optional) callback function when loading successfully.

JSON is an ideal data transmission format, it can be well integrated with JavaScript or other host language, and can be directly used by JS. Compared with the traditional method of sending "naked" data directly through GET and POST, using JSON is more reasonable in structure and more secure. As for jQuery's getJSON () function, it's just a simplified version of the ajax () function with the JSON parameter set. This function can also be used across domains and has some advantages over get () and post (). In addition, this function allows the program to execute the callback function X by writing the request url in the format "myurl?callback=X".

$.getJSON ('feed.php', {request: images, id: 001, size: large}, function (json) {alert (json.images [0] .link) / / here json is the json object returned remotely, assuming that the format is as follows: / / {'images': [/ / {link: images/001.jpg, x: 100, y: 100}, / / {link: images/002.jpg, x: 200, y 200:} / /};})

The lower-level ajax () function

Although the get () and post () functions are very simple and easy to use, some of the more complex design requirements cannot be implemented, such as making different actions at different times when ajax is sent. JQuery provides a more specific function: ajax ().

Ajax (options)

Ajax () provides a large number of parameters, so you can implement quite complex functions.

The parameter name type describes the address at which the urlString (default: current page address) sends the request. TypeString (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 only some browsers support them. TimeoutNumber sets the request timeout in milliseconds. This setting overrides the global setting. AsyncBoolean (default: true) by default, all requests are asynchronous.

If you need to send a synchronization request, set this option to false.

Note that the synchronization request will lock the browser, and other user actions must wait for the request to complete. BeforeSendFunction can modify the functions of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header.

The XMLHttpRequest object is the only parameter.

Function (XMLHttpRequest) {this; / / the options for this ajax request} function (XMLHttpRequest) {this; / / the options for this ajax request}

CacheBoolean (default: true) jQuery 1.2 new feature, set to false will not load request information from the browser cache. Callback function after the completion of the completeFunction request (called when the request succeeds or fails).

Parameter: XMLHttpRequest object, success information string.

Function (XMLHttpRequest, textStatus) {this; / / the options for this ajax request} function (XMLHttpRequest, textStatus) {this; / / the options for this ajax request} contentTypeString (default: "application/x-www-form-urlencoded") content encoding type when sending information to the server. The default value is suitable for most applications. DataObject

The data that String sends to the server. Will be automatically converted to the request string format. The GET request will be appended to the URL.

Check the description of the processData option to disable this automatic conversion. Must be in Key/Value format.

If it is an array, jQuery automatically corresponds to the same name for different values.

For example, {foo: ["bar1", "bar2"]} is converted to'& foo=bar1&foo=bar2'. The type of data that dataTypeString expects the server to return. If not specified, jQuery will automatically follow the HTTP package MIME information

Returns responseXML or responseText and passes it as a callback function parameter. Available values are:

"xml": returns the XML document, which can be processed with jQuery.

"html": returns plain text HTML information; contains script elements.

"script": returns plain text JavaScript code. The results are not automatically cached.

"json": returns JSON data.

"jsonp": JSONP format. When calling a function in the form of JSONP

Such as "myurl?callback=?" Will jQuery be replaced automatically? Is the correct function name to execute the callback function.

ErrorFunction (default: automatic judgment (xml or html)) this method is called when the request fails.

This method takes three parameters: the XMLHttpRequest object, the error message, and (possibly) the captured error object.

Function (XMLHttpRequest, textStatus, errorThrown) {/ / normally textStatus and errorThown have only one of the values this; / / the options for this ajax request} function (XMLHttpRequest, textStatus, errorThrown) {/ / normally textStatus and errorThown have only one of the values this; / / the options for this ajax request} globalBoolean (default: true) whether the global AJAX event is triggered. Setting to false will not trigger the global AJAX event

Such as ajaxStart or ajaxStop. Can be used to control different Ajax events

IfModifiedBoolean (default: false) only gets new data when the server data changes.

Use HTTP package Last-Modified header information to determine.

ProcessDataBoolean (default: true) by default, the data sent is converted to an object (not technically 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.

SuccessFunction

Call back the function after the request is successful. This method takes two parameters: the server returns the data and the status

Function (data, textStatus) {/ / data could be xmlDoc, jsonObj, html, text, etc... This; / / the options for this ajax request} function (data, textStatus) {/ / data could be xmlDoc, jsonObj, html, text, etc... This; / / the options for this ajax request}

You can specify xml, script, html, json as its data type, you can set handlers for beforeSend, error, sucess, complete and other state functions, and many other parameters can fully define the user's Ajax experience. In the following example, we use ajax () to call an XML document:

Ajax ({url: 'doc.xml', type:' GET', dataType: 'xml', timeout: 1000, error: function () {alert (' Error loading XML document');}, success: function (xml) {alert (xml)) / / here xml is the jQuery object of XML. You can use methods such as find (), next () or XPath to find nodes in it, which is no different from manipulating HTML objects with jQuery}})

Learn more about AJAX events

Some of the methods discussed above have their own event handling mechanisms, which can only be said to be local functions on the page as a whole. JQuery provides the definition of AJAX global functions to meet special needs. Here are all the functions provided by jQuery (in firing order as follows):

AjaxStart

(global event) starts a new Ajax request, and there are no other ajax requests in progress at this time

BeforeSend

(local event) triggered when an Ajax request starts. If necessary, you can set the XMLHttpRequest object here

AjaxSend

(global event) the global event triggered before the request starts

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

The global event global request was successful

Error

(local event) triggered only when an error occurs. You cannot execute both success and error callback functions at the same time

AjaxError

Triggered when an error occurs in the global event

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

Triggered when a global event global request is completed

AjaxStop

(global event) triggers when no Ajax is in progress

Local events have been introduced in previous functions, so let's mainly look at global events. If you listen for global events on an object, the AJAX actions in the global will affect it. For example, when the page is doing an AJAX operation, the p with ID of "loading" is displayed:

$("# loading") .ajaxStart (function () {$(this) .show ();})

Global events can also help you write global error and success responses without having to set them separately for each AJAX request. It is important to point out that the parameters of global events are useful. Except for ajaxStart and ajaxOptions, other events have three parameters: event, XMLHttpRequest, and ajaxOptions. The first parameter is the event itself; the second is the XHR object; and the third is the ajax parameter object that you pass. Display the global AJAX situation in an object:

$("# msg") .beforeSend (function) {$(this) .html ("requesting" + o.url);}) .ajaxSuccess (function (eMagnexhrreo) {$(this) .html (o.url + "request succeeded");}) .ajaxError (function (eMagnexhrreo) {$(this) .html (o.url + "request failed");})

Obviously, the third parameter can also help you pass the custom parameters you added to the AJAX event. When making a single AJAX request, you can set the value of global to false to make the request independent of the global event of AJAX.

$.ajax ({url: "request.php", global: false, / / disable the global Ajax event. });

If you want to set parameters for the global AJAX, you will use the ajaxSetup () function. For example, pass all AJAX requests to request.php,; to disable the global method, and force the POST method to pass:

$.ajaxSetup ({url: "request.php", global: false, type: "POST"}); that's all of the article "what are the functions in ajax?" Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report