Summary of usage of $.get(), $.post(), $.ajax(), $.getJSON() in Jquery

This article is a detailed summary of the use of $.get(), $.post(), $.ajax(), and $.getJSON() in Jquery. Friends who need it can come and refer to it, I hope it will help you help

Detailed interpretation of Jquery's Ajax functions:
$.get(), $.post(), $.ajax(), $.getJSON()

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

Description: url is the request address, data is the list of requested data, 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. select parameters.

Among them, the format of the data returned by the server is actually a string format, not the json data format we want. This reference is only for comparison and explanation.

Copy the code The code is as follows:

$.get("data.php",$("#firstName.val()"),function(data){

 

$("#getResponse").html(data); }//The returned data is a string type

);


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

 

Description: This function is similar to the $.get() parameter, with an additional type parameter, which is the requested data type, which can be html, xml, json, etc. If we set this parameter to: json, then the returned format is It is in json format. If it is not set, it is the same as the format returned by $.get(), which is a string.

Copy the code The code is as follows:

$.post("data.php",$("#firstName.val()"),function(data){

 

$("#postResponse").html(data.name);

},"json"//The type of data to be obtained is set, so the format of the obtained data is json type

);


, , $. Ajax (opiton)

 

Description: $.ajax() is a powerful function that can perform a lot of precise control on ajax. For details, please refer to the relevant information

Copy the code The code is as follows:

$.ajax({

 

url: "ajax/ajax_selectPicType.aspx",

data:{Full:"fu"},

type: "POST",

dataType:'json',

success:CallBack,

error: function (s) {

BackErr(er); }

});


四,$.getJSON(url,[data],[callback])
Copy the code The code is as follows:

$.getJSON("data.php",$("#firstName.val()"),function(jsonData){

 

$("#getJSONResponse").html(jsonData.id);}//No need to set, the data type obtained directly is json,
so you need to use jsonData.id method when calling

);


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

 

load static page

load( url, [data], [callback] );
url (String) The URL address of the requested HTML page
data (Map) (optional parameter) The key/value data sent to the server
callback (Callback) (optional parameter) The callback function when the request is completed (does not need to be success)

The load() method can easily load static page content into the specified jQuery object.

Copy the code The code is as follows:

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

In this way, the content of data.html will be loaded into the DOM object whose ID is ajax-div. You can even implement Ajax operations that load partial content by specifying an ID, such as:
Copy the code The code is as follows:

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

Implement GET and POST methods

 

get( url, [data], [callback] )
url (String) The URL address of the request.
data (Map) (optional parameter) The data to be sent to the server, expressed as a key/value pair, will be Append to the request URL as a QueryString
callback (Callback) (optional parameter) Callback function when the loading is successful (this method is called only when the return status of Response is success)

Obviously, this is a function that specifically implements the GET method, and it is quite simple to use.

Copy the code The code is as follows:

$.get('login.php', {
   id : 'Robin',
   password: '123456',
   gate : 'index'
  }, function(data, status) {
   //data is the returned object, and status is the requested status
   alert (data);
   //Assume that the server script will return a piece of text "Hello, Robin!",
then the browser will pop up a dialog box to display the text
   alert(status);
   //The result is success, error, etc., But here is the function that only runs on success
  });

post( url, [data], [callback], [type] )

 

url (String) The URL address of the request.
data (Map) (optional parameter) The data to be sent to the server, in the form of a key/value pair.
callback (Callback) (optional parameter) Callback when the load is successful Function (this method is called only when the return status of Response is success)
type (String) (optional parameter) The type of the requested data, xml, text, json, etc.

It is also a convenient function provided by jQuery, the actual usage

Copy the code The code is as follows:

$.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) The address of the JS file to be loaded
callback (Function) (optional) The callback function after successful loading

The getScript() function can remotely load and execute JavaScript scripts. 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 files according to the user's interaction, instead of having to load them all when the page is initialized.

Copy the code The code is as follows:

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

Build a bridge for data communication: getJSON()

 

getJSON(url,[data],[callback])
url (String) Sending request address
data (Map) (optional) Key/value parameter to be sent
callback (Function) (optional) Callback function when loading is successful.

JSON is an ideal data transfer format, it can be well integrated with JavaScript or other host languages, and can be used directly by JS. Compared with the traditional direct sending of "naked" data through GET and POST, using JSON is more reasonable in structure and safer. 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, which has certain advantages over get() and post(). In addition, this function can let the program execute the callback function X by writing the request url in the format of "myurl?callback=X".

Copy the code The code is as follows:

$.getJSON('feed.php',{
   request: images,
   id: 001,
   size: large
   }, function(json) {
    alert(json.images[0].link);
    //Here json is returned remotely json object, assuming its 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 get() and post() functions are very simple and easy to use, they cannot be implemented for more complex design requirements, such as making different actions during different periods of ajax sending. jQuery provides a more specific function: ajax().

 

ajax( options )
ajax() provides a large number of parameters, so it can achieve quite complex functions.

parameter name Types of describe
url String (default: current page address) The address to send the request to.
type String (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.
timeout Number Set the request timeout in milliseconds. This setting will override the global setting.
async Boolean (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 Function Functions that modify the XMLHttpRequest object before sending the request, such as adding custom HTTP headers.

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 } 
cache Boolean (default: true) New in jQuery 1.2, set to false will not load request information from browser cache.
complete Function The callback function after the request is completed (called when the request succeeds or fails).

Parameters: XMLHttpRequest object, success message 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") Content encoding type when sending information to the server. The default value is suitable for most applications.
data Object,
String
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'.
dataType String The expected data type returned by the server. If not specified, jQuery will automatically return responseXML or responseText according to the HTTP packet MIME information
, and pass it as a callback function parameter, available values:

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

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

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

"json": Returns JSON data.

"jsonp": JSONP format. When calling a function using the JSONP form,

For example "myurl?callback=?" jQuery will automatically replace ? with the correct function name to execute the callback function.

error Function (default: auto-determined (xml or html)) This method will be called when the request fails.

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

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 (默认: true) 是否触发全局 AJAX 事件。设置为 false 将不会触发全局 AJAX 事件,

如 ajaxStart 或 ajaxStop 。可用于控制不同的Ajax事件

ifModified Boolean (默认: false) 仅在服务器数据改变时获取新数据。

使用 HTTP 包 Last-Modified 头信息判断。

processData Boolean (默认: true) 默认情况下,发送的数据将被转换为对象(技术上讲并非字符串)

以配合默认内容类型 “application/x-www-form-urlencoded”。

如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。

success Function

请求成功后回调函数。这个方法有两个参数:服务器返回数据,返回状态

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 }

 

你可以指定xml、script、html、json作为其数据类型,可以为beforeSend、error、sucess、complete等状态设置 处理函数,众多其它参数也可以订完完全全定义用户的Ajax体验。下面的例子中,我们用ajax()来调用一个XML文档:

复制代码代码如下:

$.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 find(), next() or XPath to find nodes in it, which
is no different from using jQuery to manipulate HTML objects
    }
} );

Learn more about AJAX
events Some of the methods discussed above have their own event handling mechanisms. From the page as a whole, they can only be said to be local functions. jQuery provides the definition of AJAX global functions to meet special needs. Here are all the functions provided by jQuery (in order of triggering):

 

ajaxStart
(全局事件) 开始新的Ajax请求,并且此时没有其他ajax请求正在进行
beforeSend
(局部事件) 当一个Ajax请求开始时触发。如果需要,你可以在这里设置XMLHttpRequest对象
ajaxSend
(全局事件) 请求开始前触发的全局事件
success
(局部事件) 请求成功时触发。即服务器没有返回错误,返回的数据也没有错误
ajaxSuccess
全局事件全局的请求成功
error
(局部事件) 仅当发生错误时触发。你无法同时执行success和error两个回调函数
ajaxError
全局事件全局的发生错误时触发
complete
(局部事件) 不管你请求成功还是失败,即便是同步请求,你都能在请求完成时触发这个事件
ajaxComplete
全局事件全局的请求完成时触发
ajaxStop
(全局事件) 当没有Ajax正在进行中的时候,触发
局部事件在之前的函数中都有介绍,我们主要来看看全局事件。对某个对象进行全局事件监听,那么全局中的AJAX动作,都会对其产生影响。比如,当页面在进行AJAX操作时,ID为”loading”的DIV就显示出来:

复制代码代码如下:

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

Global events can also help you write global error and success responses without having to set them up individually for each AJAX request. It is important to point out that the parameters of the global event 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; the third is the ajax parameter object you pass. Display the global AJAX situation in an object:
Copy the code The code is as follows:

$("#msg").beforeSend(function(e,xhr,o) {
 $(this).html("Requesting"+o.url);
 }).ajaxSuccess(function(e,xhr,o) {
 $(this).html(o.url+"Request succeeded");
 }).ajaxError(function(e,xhr,o) {
 $(this).html(o.url+"Request failed");
});

Obviously, the third parameter can also help you pass custom parameters you add in the AJAX event. On a single AJAX request, you can set the value of global to false to separate the request from the AJAX global event.
Copy the code The code is as follows:

$.ajax({
   url: "request.php",
   global: false,
   // Disable global Ajax events.
 });

If you want to set parameters for global AJAX, you will use the ajaxSetup() function. For example, to pass all AJAX requests to request.php, ;disable global methods; force delivery with POST method:
Copy the code The code is as follows:

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

Some of the methods you have to know
Writing AJAX is definitely inseparable from getting the corresponding value from the page. Here are just a few of the methods:

 

val() 
The val() function can return the value of a form component, such as the value of any kind of input. With the selector operation, you can easily get the value of the option group, input box, button and other elements.

Copy the code The code is as follows:

$("input[name='info']:text").val();
//Return the value of the text box named info
$("input[name='pass']:password").val() ;
//Return the value of the password box named pass
$("input[name='save']:radio").val();
//Return the value of the single option named save
//and so on

serialize()

 

The serialize function can help you convert all the values ​​of the form object to a sequence of strings. This is very convenient if you want to write a GET request.
serializeArray() is similar to serialize() except that it returns a JSON object.

PS: This site also provides several powerful json parsing, conversion and formatting tools for you to choose and use. I believe it will be helpful for your next json format data processing:

Online JSON code inspection, inspection, beautification, formatting tools:
http://tools.jb51.net/code/json

Online XML/JSON conversion:
http://tools.jb51.net/code/xmljson

JSON code online formatting/beautification/compression/editing/conversion tool:
http://tools.jb51.net/code/jsoncodeformat

C语言风格/HTML/CSS/json代码格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json

本文转自:https://www.cnblogs.com/gxbk629/p/5795568.html

Guess you like

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