Home  >  Article  >  Web Front-end  >  Detailed explanation of the use of Jquery's get, post, ajax, and getJSON functions

Detailed explanation of the use of Jquery's get, post, ajax, and getJSON functions

php中世界最好的语言
php中世界最好的语言Original
2018-04-25 16:28:081774browse

This time I will bring you a detailed explanation of the use of Jquery's get, post, ajax, and getJSON functions. What are the precautions for using Jquery's get, post, ajax, and getJSON functions. The following are practical cases. Let’s take a look.

It has reference value. Friends who need it can refer to

1, $.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 one is returned by the server Data, the second parameter is the status of the server, which is an optional parameter.

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

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

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

Explanation: This function has similar parameters to $.get(), with more parameters There is a type parameter, type is the requested

data type, which can be html, xml, json and other types. If we set this parameter to: json, then the returned format will be json format. If it is not set , just like the format returned by $.get(), they are all strings $.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);

3. $.ajax(opiton)

Description: $.ajax() is a powerful function that can perform many precise controls on ajax. If you need detailed explanation, please refer to the relevant information

$.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])

$ .getJSON("data.php",$("#firstName.val()"),function(jsonData){$("#getJSONResponse").html(jsonData.id);}//No need to set, get it directly The data type is json, so the jsonData.id method needs to be used when calling);

When Ajax meets jQuery There are more and more AJAX-based applications, and for front-end developers, they have to deal directly with the underlying HTTPRequest Not a pleasant thing. Since jQuery encapsulates

JavaScript, the issue of AJAX application 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 that everyone is already familiar with jQuery syntax, so let's 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)
load() method can easily Load static page content into the specified jQuery object. $('#ajax-p').load('data.html');
In this way, the content of data.html will be loaded into the DOM object with the ID ajax-p. You can even implement the Ajax operation of loading part of the content by specifying the ID, such as:
$('#ajax-p').load('data.html#my-section');

Implement GET and POST methods

get( url, [data], [callback] ) 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, 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 the Response is success)

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

$.get('login.php', { id : 'Robin', password: '123456', gate : 'index' }, function(data, status) { //data为返回对象,status为请求的状态 alert(data); //此时假设服务器脚本会返回一段文字"你好,Robin!",那么浏览器就会弹出对话框显示该段文字 
alert(status); //结果为success, error等等,但这里是成功时才能运行的函数 });
post( url, [data], [callback], [type] ) url (String) 发送请求的URL地址.
data (Map)(可选参数) 要发送给服务器的数据,以 Key/value 的键值对形式表示
callback (Callback) (可选参数) 载入成功时回调函数(只有当Response的返回状态是success才是调用该方法)
type (String) (可选参数) 请求数据的类型,xml,text,json等
同样是jQuery提供的一个简便函数,其实用法$.post('regsiter.php', { id:'Robin', password: '123456', type:'user' },function(data, status) { alert(data); }, "json");
Event-driven script loading Input function: getScript()

getScript( url, [callback] ) url (String) Address of JS file to be loaded

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

getScript() 函数可以远程载入JavaScript脚本并且执行。这个函数可以跨 域载入JS文件(神奇……?!)。这个函数的意义是巨大 的,它可以很大程度的缩减页面初次载入的代码量,因为你可以根据用户的交互来载入相应的JS文件,而不必在页面初始化的时候全部载入。

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

构建数据通讯的桥梁:getJSON()

getJSON(url,[data],[callback]) url (String) 发送请求地址

data (Map) (可选) 待发送 Key/value 参数

callback (Function) (可选) 载入成功时回调函数。

JSON 是一种理想的数据传输格式,它能够很好的融合与JavaScript或其他宿主语 言,并且可以被JS直接使用。使用JSON相比传统的通过 GET、POST直接发送”裸体”数据,在结构上更为合理,也更为安全。至于jQuery的getJSON()函数,只是设置了JSON参数的 ajax()函数的一个简化版本。

这个函数也是可以跨域使用的,相比get()、post()有一定优势。另外这个函数可以通过把请求url写 成”myurl?callback=X”这种格式,让程序执行回调函数X。

$.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:} 
//]}; 
} );

更底层的ajax()函数

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

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

你 可以指定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); 
//此处xml就是XML的jQuery对象了,你可以用find()、next()或XPath等方法在里面寻找节点,和用jQuery操作HTML对象没有区别 
}});

进一步了解AJAX事件

前面讨论的一些方法都有自己的事件处理机制,从页面整体来说,都只能说是局部函数。jQuery提供了AJAX全局函数的定义,以满足特殊的需求。下面是jQuery提供的所有函数(按照触发顺序排列如下):

ajaxStart (全局事件) 开始新的Ajax请求,并且此时没有其他ajax请求正在进行 beforeSend (局部事件) 当一个Ajax请求开始时触发。如果需要,你可以在这里设置XMLHttpRequest对象 ajaxSend (全局事件) 请求开始前触发的全局事件 success (局部事件) 请求成功时触发。即服务器没有返回错误,返回的数据也没有错误 ajaxSuccess 全局事件全局的请求成功 error (局部事件) 仅当发生错误时触发。

你无法同时执行success和error两个回调函数 ajaxError 全局事件全局的发生错误时触发 complete (局部事件) 不管你请求成功还是失败,即便是同步请求,你都能在请求完成时触发这个事件 ajaxComplete 全局事件全局的请求完成时触发 ajaxStop (全局事件) 当没有Ajax正在进行中的时候,触发局部事件在之前的函数中都有介绍,我们主要来看看全局事件。对某个对象进行全局事件监听,那么全局中的AJAX动作,都会对其产生影响。比如,当页面在进行AJAX操作时,ID为”loading”的p就显示出来:

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

全局事件也可以帮助你编写全局的错误相应和成功相应,而不需要为每个AJAX请求独立设置。有必要指出,全局事件的参数是很有用的。除了 ajaxStart、ajaxOptions,其他事件均有event, XMLHttpRequest, ajaxOptions三个参数。第一个参数即事件本身;第二个是XHR对象;第三个是你传递的ajax参数对象。在一个对象里显示全局的AJAX情况:

$("#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+"请求失败");});

很显然,第三个参数也可以帮助你传递你在AJAX事件里加入的自定义参数。
在单个AJAX请求时,你可以将global的值设为false,以将此请求独立于AJAX的全局事件。

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

如果你想为全局AJAX设置参数,你会用上ajaxSetup()函数。

例如,将所有AJAX请求都传递到request.php,;禁用全局方法;强制用POST方法传递:

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

一些你不得不知道的方法

写AJAX肯定离不开从页面获取相应的值。在这里简单列举一些方法:

val() val()函数可以返回表单组建的值,例如任何种类input的值。

配合选择符操作,你可以轻易获取选项组、输入框、按钮等元素的值。

$("input[name='info']:text").val();//返回名字为info的文本框的值$("input[name='pass']:password").val();//返回名字为pass的密码框的值
$("input[name='save']:radio").val();//返回名字为save的单选项的值//以此类推serialize() serialize函数可以帮你把表单对象的所有值都转换为字符串序列。

如果你要写GET格式的请求,这个就非常方便了。

serializeArray() 和serialize()类似,只不过它返回的是JSON对象。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样局部更新Razor页面

ajax如何做出页面局部跳转功能

The above is the detailed content of Detailed explanation of the use of Jquery's get, post, ajax, and getJSON functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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