Home > Web Front-end > JS Tutorial > Summary of usage of $.get(),$.post(),$.ajax(),$.getJSON() in Jquery_jquery

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

WBOY
Release: 2016-05-16 17:15:23
Original
960 people have browsed it

Detailed interpretation of each Jquery Ajax function:
$.get(), $.post(), $.ajax(), $.getJSON()

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

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

Among them, the format of the data returned by the server is actually in the form of a string, which is not the json data format we want. It is quoted here just for comparison and illustration

Copy Code The code is as follows:

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

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

);


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

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

Copy code The code is as follows:

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

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

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

);


Three, $.ajax(opiton)

Note: The $.ajax() function is powerful and can control ajax accurately. If you need detailed explanation, please refer to the relevant information

Copy code The code is as follows:

$.ajax({

url: "ajax/ajax_selectPicType.aspx",

data:{Full:"fu"},

type: "POST",

dataType:'json',

success:CallBack,

error:function(er){

BackErr(er);}

});


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

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

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

);


When Ajax meets jQuery There are more and more AJAX-based applications, and for front-end developers, it is not pleasant to deal directly with the underlying HTTPRequest matter. Since jQuery encapsulates JavaScript, AJAX applications must have been considered. Indeed, if you use jQuery to write AJAX, it will be N times more convenient than writing it directly in JS. (I wonder if I will lose my knowledge of JS after using jQuery for a long time...) It is assumed here that everyone is familiar with jQuery syntax, and I will make some summary of some applications of ajax.

Load static page

load( url, [data], [callback] );
url (String) URL address of the requested HTML page
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 successful)

The

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

Copy 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 with the ID ajax-div. You can even implement the Ajax operation of loading part of the content by specifying the 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 to send the request.
data (Map) (optional parameter) The data to be sent to the server, with Key/ The key-value pair form of value will be appended to the request URL as QueryString
callback (Callback) (optional parameter) callback function when 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 return object, status is the status of the request
alert(data);
//At this time, it is assumed that the server script will return a 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 can only be run when successful
});

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

url (String) URL address to send the request.
data (Map) (optional parameter) The data to be sent to the server, expressed in the form of Key/value pairs
callback (Callback) ( Optional parameters) Callback function when loading is successful (this method is called only when the return status of Response is success)
type (String) (optional parameters) Type of requested data, xml, text, json, etc.

is also a simple function provided by jQuery. Its usage is

Copy 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) JS file address to be loaded
callback (Function) (optional) 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 for the initial loading of the page, because you can load the corresponding JS files based on user interaction instead of loading them all when the page is initialized.

Copy code The code is as follows:

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

Build a bridge for data communication: getJSON()

getJSON(url,[data],[callback])
url (String) Send 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 transmission format. It can be well integrated with JavaScript or other host languages ​​and can be used directly by JS. Using JSON is more structurally reasonable and safer than sending "nude" data directly through traditional GET and POST. As for jQuery's getJSON() function, it is just a simplified version of the ajax() function with JSON parameters set. This function can also be used across domains and 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 code The code is as follows:

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

更底层的ajax()函数
虽然get()和post()函数非常简洁易用,但是对于更复杂的一些设计需求还是无法实现,比如在ajax发送的不同时段做出不同的动作等。jQuery提供一个更为具体的函数:ajax()。

ajax( options )
ajax()提供了一大票参数,所以可以实现相当复杂的功能。

参数名 类型 描述
url String (默认: 当前页地址) 发送请求的地址。
type String (默认: “GET”) 请求方式 (“POST” 或 “GET”), 默认为 “GET”。
注意:其它 HTTP 请求方法,如 PUT 和 DELETE 也可以使用,但仅部分浏览器支持。
timeout Number 设置请求超时时间(毫秒)。此设置将覆盖全局设置。
async Boolean (默认: true) 默认设置下,所有请求均为异步请求。
如果需要发送同步请求,请将此选项设置为 false。
注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
beforeSend Function 发送请求前可修改 XMLHttpRequest 对象的函数,如添加自定义 HTTP 头。

XMLHttpRequest 对象是唯一的参数。

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

cache Boolean (默认: true) jQuery 1.2 新功能,设置为 false 将不会从浏览器缓存中加载请求信息。
complete Function 请求完成后回调函数 (请求成功或失败时均调用)。

参数: XMLHttpRequest 对象,成功信息字符串。

function (XMLHttpRequest, textStatus) { this; // the options for this ajax request } function (XMLHttpRequest, textStatus) { this; // the options for this ajax request }
contentType String (默认: “application/x-www-form-urlencoded”) 发送信息至服务器时内容编码类型。默认值适合大多数应用场合。
data Object,
String
发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。
查看 processData 选项说明以禁止此自动转换。必须为 Key/Value 格式。
如果为数组,jQuery 将自动为不同值对应同一个名称。
如 {foo:["bar1", "bar2"]} 转换为 ‘&foo=bar1&foo=bar2′。
dataType String 预期服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息
返回 responseXML 或 responseText,并作为回调函数参数传递,可用值:

“xml”: 返回 XML 文档,可用 jQuery 处理。

“html”: 返回纯文本 HTML 信息;包含 script 元素。

“script”: 返回纯文本 JavaScript 代码。不会自动缓存结果。

“json”: 返回 JSON 数据 。

“jsonp”: JSONP 格式。使用 JSONP 形式调用函数时,

如 “myurl?callback=?” jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。

error Function (默认: 自动判断 (xml 或 html)) 请求失败时将调用此方法。

这个方法有三个参数:XMLHttpRequest 对象,错误信息,(可能)捕获的错误对象。

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 }

You can specify xml, script, html, json as its data type, and you can set processing functions for beforeSend, error, success, complete and other states. Many other parameters can also be customized to completely define the user's Ajax experience. In the following example, we use ajax() to call an XML document:

Copy code The code is as follows:

$.ajax({
url: 'doc.xml',
type: 'GET',
dataType: 'xml',
timeout: 1000,
error: function(){
alert('Error loading XML document');
},
success: function(xml){
alert(xml);
//xml here is XML jQuery object, you can use methods such as find(), next() or >
Learn more about AJAX events
Some of the methods discussed earlier have their own event processing mechanisms. From the perspective of 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 (arranged in order of triggering):

ajaxStart
(global event) starts a new Ajax request, and there are no other ajax requests in progress at this time
beforeSend
(local event) triggers when an Ajax request starts. If necessary, you can set the XMLHttpRequest object here ajaxSend

(global event) global event triggered before the request starts
success
(local event) triggered when the request is successful. That is, the server does not return an error, and the returned data has no errors
ajaxSuccess
Global event Global request success
error
(local event) is only triggered when an error occurs. You cannot execute the success and error callback functions at the same time
ajaxError
Global event The global event is triggered when an error occurs
complete
(local event) Whether your request succeeds or fails, even if it is a synchronous request, you This event can be triggered when the request is completed
ajaxComplete
Global event The global event is triggered when the request is completed
ajaxStop
(global event) When no Ajax is in progress, the
local event is triggered It has been introduced in the previous functions, let’s mainly look at global events. If global event monitoring is performed on an object, all AJAX actions in the world will have an impact on it. For example, when the page is performing AJAX operations, the DIV with the ID "loading" is displayed:




Copy the code

The code is as follows: $("#loading").ajaxStart(function(){ $(this).show(); });

Global events can also help you write global error and success responses without having to set them independently for each AJAX request. It is necessary to point out that the parameters of global events are very 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 you passed. Display the global AJAX situation in an object:



Copy 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 successful");
}).ajaxError(function(e,xhr,o) {
$(this).html(o .url "Request failed");
});


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 AJAX global events.



Copy 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 ajaxSetup ()function. For example, pass all AJAX requests to request.php; disable global methods; force POST method delivery:



Copy code
The code is as follows: $.ajaxSetup({ url: "request.php", global: false,
type: "POST"
});


알아야 할 몇 가지 방법
AJAX를 작성하는 것과 페이지에서 해당 값을 얻는 것은 확실히 불가분의 관계입니다. 다음은 몇 가지 간단한 방법입니다.

val()
val() 함수는 모든 유형의 입력 값과 같은 양식 구성 요소의 값을 반환할 수 있습니다. 선택기 작업을 사용하면 옵션 그룹, 입력 상자, 버튼 및 기타 요소의 값을 쉽게 얻을 수 있습니다.

코드 복사 코드는 다음과 같습니다.

$("input[name='info ']: text").val();
//info
$("input[name='pass']:password").val();// pass라는 이름의 비밀번호 상자 값을 반환합니다
$("input[name='save']:radio").val();
//save라는 단일 옵션의 값을 반환합니다
/ /기타

직렬화()
직렬화 기능을 사용하면 양식 개체의 모든 값을 문자열 시퀀스로 변환할 수 있습니다. 이는 GET 형식으로 요청을 작성하려는 경우 매우 편리합니다.

serializeArray()는 JSON 객체를 반환한다는 점을 제외하면 serialize()와 유사합니다.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template