Summary of usage of "go" jquery in $.get (), $.post (), $.load (), $.ajax (), $.getjson (), $.getscript ()

Source: Internet
Author: User
Tags event listener getscript browser cache

A, $.get (Url,[data],[callback])

Implementing the Get Method

Description
URL (String) to send the requested URL address.
Data (MAP) (optional parameter) to be sent to the server, expressed as a Key/value key-value pair, is appended to the request URL as QueryString
Callback (callback) (optional parameter) when loading a successful callback function (only if the return state of response is success the method is called), the function accepts two parameters, the first is the data returned by the server, the second parameter is the state of the server, is an optional parameter.

In this case, the format of the server return data is actually a string situation, not the JSON data format we want, which is quoted only for comparison purposes.

Obviously this is a function to implement get mode, and it is quite simple to use.

The code is as follows:

$.get("data.php",$("#firstName.val()"),function(data){$("#getResponse").html(data); }//返回的data是字符串类型);

The code is as follows:

$.get(‘login.php‘, {   id      : ‘Robin‘,   password: ‘123456‘,   gate    : ‘index‘  }, function(data, status) { //data为返回对象,status为请求的状态 alert(data); //此时假设服务器脚本会返回一段文字"你好,Robin!",那么浏览器就会弹出对话框显示该段文字 alert(status); //结果为success, error等等,但这里是成功时才能运行的函数 });

II, $.post (Url,[data],[callback],[type])

Implementing the Post Method

Description
URL (String) to send the requested URL address.
Data (MAP) (optional parameter) to be sent to the server, expressed as a Key/value key-value pair
Callback (callback) (optional parameter) The callback function when loading succeeds (only if the return state of response is success the method is called)
Type (String) (optional parameter) request data types, Xml,text,json, etc.

This function is also a simple function of jquery, similar to the $.get () parameter, with a type parameter, type of the requested data type, can be a type of Html,xml,json, if we set this parameter to: JSON, The returned format is in JSON format and, if not set, is the same as the format returned by $.get (), which is a string.

The code is as follows:

$.post("data.php",$("#firstName.val()"),function(data){ $("#postResponse").html(data.name); },"json"//设置了获取数据的类型,所以得到的数据格式为json类型的);

The code is as follows:

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

Three, $.load (URL, [data], [callback])

Loading static pages

Description
URL address of the URL (String) of the requested HTML page
Data (MAP) (optional parameters) sent to the server Key/value
Callback (callback) (optional parameter) callback function when the request is complete (does not need to be success)

The load () method can easily load static page content into a specified jquery object.

The code is as follows:

$(‘#ajax-div‘).load(‘data.html‘);

In this way, the contents of the data.html will be loaded into the DOM object with ID ajax-div. You can even implement an AJAX operation that loads some content by making an ID, such as:

The code is as follows:

$(‘#ajax-div‘).load(‘data.html#my-section‘);

Four, $.getscript (URL, [callback])

Event-driven script loading function

Description
URL (String) to be loaded into the JS file address
Callback (function) (optional) After successful load callback function

The GetScript () function can be loaded remotely into JavaScript scripts and executed. This function can be loaded into JS files across domains (magical ...!!). )。 The meaning of this function is huge, it can greatly reduce the amount of code that the page loads initially, because you can load the corresponding JS file according to the user's interaction, without having to load it all when the page is initialized.
The code is as follows:

$.getScript(‘ajaxEvent.js‘, function() {   alert("Scripts Loaded!"); //载入ajaxEvent.js,并且在成功载入后显示对话框提示。 });

Five, $.getjson (Url,[data],[callback])

Building a bridge for data communication: Getjson ()

Description
URL (String) to send the request address
Data (MAP) (optional) Key/value parameters to be sent
Callback (function) (optional) The callback function when loading succeeds.

JSON is an ideal data transmission format, it can be well fused with JavaScript or other host language, and can be used directly by JS. Using JSON to send "naked" data directly through GET, post, is structurally more reasonable and more secure. As for jquery's Getjson () function, it's just a simplified version of the Ajax () function that sets the JSON parameter. This function can also be used across domains, with a certain advantage over get () and post (). In addition, this function can be used to write the request URL as a "myurl?callback=x" format, so that the program executes the callback function X.

The code is as follows:

$.getJSON(‘feed.php‘,{   request: images,   id:      001,   size:    large   }, function(json) { alert(json.images[0].link); //此处json就是远程传回的json对象,假设其格式如下: //{‘images‘ : [ // {link: images/001.jpg, x :100, y : 100}, // {link: images/002.jpg, x : 200, y 200:} //]}; } );

The code is as follows:

$.getJSON("data.php",$("#firstName.val()"),function(jsonData){ //无需设置,直接获取的数据类型为json,所以调用时需要使用jsonData.id方式 $("#getJSONResponse").html(jsonData.id);});

Liu, $.ajax (Opiton)

Lower-level Ajax () functions
Although the get () and post () functions are very simple and easy to use, some of the more complex design requirements are not achievable, such as making different moves during the different periods of time that Ajax sends. jquery provides a more specific function: Ajax ().

Description
$.ajax () This function is powerful, you can do a lot of precise control of Ajax, please refer to the relevant information for detailed instructions
The code is as follows:

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

Ajax (Options)

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

The

Parameter name type describes  
URL String (default: Current page address) sends the requested address.  
Type String (default: "Get") Request method ("POST" or "get"), the default is "get". Note: Other HTTP request methods, such as PUT and DELETE, can also be used, but only some browsers support it.  
Timeout number sets the request time-out (in milliseconds). This setting overrides the global settings.  
Async Boolean (default: TRUE) The default setting, all requests are asynchronous requests. If you need to send a synchronization request, set this option to false. Note that the sync request will lock the browser, and the user's other actions must wait for the request to complete before it can be executed. &NBSP
Beforesend function can modify XMLHttpRequest objects before sending a request, such as adding a custom HTTP header.   The
XMLHttpRequest object is a unique parameter.

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

The cache Boolean (default: TRUE) JQuery 1.2 new feature, set to False will not load the request information from the browser cache.
The callback function after complete function request is completed (called when the request succeeds or fails).

Parameters: 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 }

ContentType String (default: "application/x-www-form-urlencoded") the content encoding type when sending information to the server. The default values are suitable for most applications.
Data Object,
String to send data to the server. is automatically converted to the request string format. The GET request will be appended to the URL.
View the ProcessData option description to disallow this automatic conversion. Must be a key/value format.
If an array, JQuery automatically corresponds to the same name for the different values.
such as {foo:["bar1", "Bar2"]} is converted to ' &foo=bar1&foo=bar2′.
DataType String expects the data type returned by the server. If not specified, JQuery will automatically be based on the HTTP packet MIME information
Returns Responsexml or ResponseText, and is passed as a callback function parameter, with the available values:

"XML": Returns an XML document that can be processed with jQuery.

HTML: Returns plain text HTML information, including the script element.

"Script": Returns plain text JavaScript code. Results are not automatically cached.

"JSON": Returns the JSON data.

"JSONP": Jsonp format. When a function is called using the JSONP form,

Like "myurl?callback=?" JQuery will be replaced automatically? is the correct function name to execute the callback function.
This method is called when the error Function (default: Automatic judgment (XML or HTML)) requests fail.

function (XMLHttpRequest, textStatus, errorThrown) { 
// 通常情况下textStatus和errorThown只有其中一个有值 this; 
// the options for this ajax request 

function (XMLHttpRequest, textStatus, errorThrown) { 
// 通常情况下textStatus和errorThown只有其中一个有值 this; 
// the options for this ajax request 
}

Global Boolean (default: TRUE) to trigger an overall AJAX event. Setting to False will not trigger a global AJAX event.

such as Ajaxstart or Ajaxstop. Can be used to control different AJAX events
Ifmodified Boolean (default: false) only gets new data when the server data changes.

Use the HTTP packet last-modified header information to determine.
ProcessData Boolean (default: TRUE) the sent data is converted to an object by default (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.
Success Function

The callback function after the request succeeds. This method has two parameters: the server returns data, returns the status
function (data, textstatus) {//data could be xmldoc, jsonobj, HTML, text, etc ... this;//the options for this Ajax reques T} function (data, textstatus) {//data could be xmldoc, jsonobj, HTML, text, etc ... this;//the options for this Ajax re Quest}

You can specify XML, script, HTML, JSON as its data type, you can set the processing function for Beforesend, error, sucess, complete and other states, and many other parameters can also be customized to completely define the user's Ajax experience. In the following example, we use Ajax () to invoke an XML document:
The code is as follows:

$.ajax({    ‘doc.xml‘,    type: ‘GET‘,    dataType: ‘xml‘,    timeout: 1000, error: function(){ alert(‘Error loading XML document‘); }, success: function(xml){ alert(xml); //此处xml就是XML的jQuery对象了,你可以用find()、next()或XPath等方法在里面寻找节点,和用jQuery操作HTML对象没有区别 }});

Learn more about AJAX events

Some of the methods discussed earlier have their own event handling mechanism, which can only be described as local functions from the overall page. jquery provides the definition of an AJAX global function to meet specific requirements. The following are all the functions provided by jquery (in the order of the triggering sequence below):

Ajaxstart
(global event) starts a new AJAX request, and no other AJAX request is in progress at this time
Beforesend
(local event) is triggered when an AJAX request starts. If necessary, you can set the XMLHttpRequest object here
Ajaxsend
Global event triggered before the request starts (global event)
Success
triggered when the request is successful (local event). That is, the server does not return an error and the returned data is not error
Ajaxsuccess
Global Event Global Request succeeded
Error
(local event) is triggered only when an error occurs. You cannot perform both success and error two callback functions at the same time
Ajaxerror
Global event triggered when an error occurs globally
Complete
(local event) Whether you request success or failure, even if the request is synchronous, you can trigger the event when the request is complete
Ajaxcomplete
triggered when global event global request completes
Ajaxstop
(global event) triggered when no Ajax is in progress
Local events are described in previous functions, and we look at global events in the main. A global event listener for an object will have an impact on the global Ajax action. For example, when the page is doing an AJAX operation, the DIV with the id "loading" is displayed:
The code is as follows:

$ ("#loading"). Ajaxstart (function () {
$ (this). Show ();
});

Global events can also help you write global errors appropriately and successfully accordingly, without having to set up independently for each AJAX request. It is necessary to point out that the parameters of the global event are useful. In addition to Ajaxstart, Ajaxoptions, other events have event, XMLHttpRequest, ajaxoptions three parameters. The first parameter is the event itself, the second is the XHR object, and the third is the Ajax parameter object that you passed. Displays the global AJAX situation in an object:

The code is as follows:

$("#msg").beforeSend(function(e,xhr,o) { $(this).html("正在请求"+o.url); }).ajaxSuccess(function(e,xhr,o) { $(this).html(o.url+"请求成功"); }).ajaxError(function(e,xhr,o) { $(this).html(o.url+"请求失败");});

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

The code is as follows:

$.ajax({   url: "request.php",   global: false, // 禁用全局Ajax事件. });

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

The code is as follows:

$.ajaxSetup({  url: "request.php", global: false, type: "POST"});

Some of the ways you have to know
Ajax must be written to get the corresponding value from the page. Here are some simple ways to enumerate:

Val ()
The Val () function can return the value of a form's build, such as the value of any kind of input. With the selector action, you can easily get the value of an option group, input box, button, and so on.

The code is as follows:

$("input[name=‘info‘]:text").val();//返回名字为info的文本框的值$("input[name=‘pass‘]:password").val();//返回名字为pass的密码框的值$("input[name=‘save‘]:radio").val();//返回名字为save的单选项的值//以此类推

Serialize ()

The Serialize function can help you convert all the values of a Form object to a sequence of strings. This is handy if you want to write a get format request.
Serializearray () is similar to serialize () except that it returns a JSON object.

Summary of usage of "go" jquery in $.get (), $.post (), $.load (), $.ajax (), $.getjson (), $.getscript ()

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.