$.post and $.get are simple methods. If you want to handle complex logic, you still need to use jQuery.ajax()
1. General format of $.ajax
$.ajax({ type: 'POST', url: url , data: data , success: success , dataType: dataType });
2. Parameter description of $.ajax
Parameter Description
url | Required. Specifies the URL to which the request should be sent. | ||||||||
data | Optional. Map or string value. Specifies the data to be sent to the server with the request. | ||||||||
success(data, textStatus, jqXHR) | Optional. The callback function executed when the request is successful. | ||||||||
dataType |
|
三、$.ajax需要注意的一些地方:
1.data主要方式有三种,html拼接的,json数组,form表单经serialize()序列化的;通过dataType指定,不指定智能判断。
2.$.ajax只提交form以文本方式,如果异步提交包含
四、$.ajax我的实际应用例子
//1.$.ajax带json数据的异步请求 var aj = $.ajax( { url:'productManager_reverseUpdate',// 跳转到 action data:{ selRollBack : selRollBack, selOperatorsCode : selOperatorsCode, PROVINCECODE : PROVINCECODE, pass2 : pass2 }, type:'post', cache:false, dataType:'json', success:function(data) { if(data.msg =="true" ){ // view("修改成功!"); alert("修改成功!"); window.location.reload(); }else{ view(data.msg); } }, error : function() { // view("异常!"); alert("异常!"); } }); //2.$.ajax序列化表格内容为字符串的异步请求 function noTips(){ var formParam = $("#form1").serialize();//序列化表格内容为字符串 $.ajax({ type:'post', url:'Notice_noTipsNotice', data:formParam, cache:false, dataType:'json', success:function(data){ } }); } //3.$.ajax拼接url的异步请求 var yz=$.ajax({ type:'post', url:'validatePwd2_checkPwd2?password2='+password2, data:{}, cache:false, dataType:'json', success:function(data){ if( data.msg =="false" ) //服务器返回false,就将validatePassword2的值改为pwd2Error,这是异步,需要考虑返回时间 { textPassword2.html("<font color='red'>业务密码不正确!</font>"); $("#validatePassword2").val("pwd2Error"); checkPassword2 = false; return; } }, error:function(){} }); //4.$.ajax拼接data的异步请求 $.ajax({ url:'<%=request.getContextPath()%>/kc/kc_checkMerNameUnique.action', type:'post', data:'merName='+values, async : false, //默认为true 异步 error:function(){ alert('error'); }, success:function(data){ $("#"+divs).html(data); } });
url: The requirement is a String type parameter, (default is the current page address) the address to which the request is sent.
type: The parameter is required to be of String type, and the request method (post or get) defaults to get. Note other http request methods such as put and
delete can also be used, but only some browsers support it.
timeout: It is required to be a parameter of type Number, set the request timeout (milliseconds). This setting will override the global setting of the $.ajaxSetup() method
Set.
async: requires parameters of Boolean type. The default setting is true. All requests are asynchronous requests.
Set this option to false if you need to send synchronous requests. Note that synchronous requests will lock the browser and the user must wait for other operations
It can only be executed after the request is completed.
cache: requires parameters of Boolean type, defaults to true (when dataType is script, defaults to false).
Setting to false will not load request information from the browser cache.
data: Requires parameters of type Object or String, data sent to the server. If it is not a string, it will be automatically converted into a string format
Formula. The get request will be appended to the url. To prevent this automatic conversion, check the processData option. The object must be in key/value format
formula, for example, {foo1:"bar1",foo2:"bar2"} is converted to &foo1=bar1&foo2=bar2. If it is an array, JQuery will automatically be different
Values correspond to the same name. For example, {foo:["bar1","bar2"]} is converted to &foo=bar1&foo=bar2.
dataType: Parameters required to be String type, the data type expected to be returned by the server. If not specified, JQuery will automatically base the http package on mime
The information is returned as responseXML or responseText and passed as callback function parameter.
Available types are as follows:
xml: Returns an XML document that can be processed with JQuery.
html: Returns plain text HTML information; the included script tag will be executed when inserted into the DOM.
script: Returns plain text JavaScript code. Results are not cached automatically. Unless cache parameters are set. Note that in remote requests
(not under the same domain), all post requests will be converted into get requests.
json: Return JSON data.
jsonp: JSONP format. When calling a function using the SONP form, such as myurl?callback=?, JQuery will automatically replace the last
"?" is the correct function name to execute the callback function.
text: Returns a plain text string.
beforeSend: The parameter is required to be a Function type. You can modify the function of the XMLHttpRequest object before sending the request, such as adding a custom
HTTP header. If false is returned in beforeSend, this ajax request can be canceled. The XMLHttpRequest object is the only parameter
Number.
function(XMLHttpRequest){
this; //The options parameters passed when calling this ajax request
}
complete: The parameter is required to be Function type, and the callback function is called after the request is completed (called when the request succeeds or fails).
Parameters: XMLHttpRequest object and a string describing the successful request type.
function(XMLHttpRequest, textStatus){
this; //The options parameters passed when calling this ajax request
}
Success: The parameter is required to be Function type. The callback function called after the request is successful has two parameters.
(1) Data returned by the server and processed according to the dataType parameter.
(2) A string describing the status.
function(data, textStatus){
//data may be xmlDoc, jsonObj, html, text, etc.
this; //The options parameters passed when calling this ajax request
error: The parameter is required to be Function type, and the function is called when the request fails. This function has 3 parameters, namely XMLHttpRequest object, error
Error message, captured error object (optional).
The ajax event function is as follows:
function(XMLHttpRequest, textStatus, errorThrown){
//Normally only one of textStatus and errorThrown contains information
this; //The options parameters passed when calling this ajax request
}
contentType: requires a parameter of String type. When sending information to the server, the content encoding type defaults to
is "application/x-www-form-urlencoded". This default value is suitable for most applications.
dataFilter: requires parameters of Function type, a function that preprocesses the original data returned by Ajax.
Provide two parameters: data and type. data is the original data returned by Ajax, and type is provided when calling jQuery.ajax
dataType parameter. The value returned by the function will be further processed by jQuery.
function(data, type){
//Return the processed data
return data;
}
global: requires parameters of Boolean type, defaults to true. Indicates whether to trigger the global ajax event. Setting to false will not trigger the global
ajax event, ajaxStart or ajaxStop can be used to control various ajax events.
ifModified: requires a Boolean type parameter, the default is false. Only get new data when server data changes.
The basis for judging server data changes is the Last-Modified header information. The default value is false, which means header information is ignored.
jsonp: requires parameters of String type, rewrites the name of the callback function in a jsonp request.
该值用来替代在"callback=?"这种GET或POST请求中URL参数里的"callback"部分,例如
{jsonp:'onJsonPLoad'}会导致将"onJsonPLoad=?"传给服务器。
username:要求为String类型的参数,用于响应HTTP访问认证请求的用户名。
password:要求为String类型的参数,用于响应HTTP访问认证请求的密码。
processData:要求为Boolean类型的参数,默认为true。默认情况下,发送的数据将被转换为对象(从技术角度
来讲并非字符串)以配合默认内容类型"application/x-www-form-urlencoded"。如果要发送DOM
树信息或者其他不希望转换的信息,请设置为false。
scriptCharset:要求为String类型的参数,只有当请求时dataType为"jsonp"或者"script",并且type是GET时
才会用于强制修改字符集(charset)。通常在本地和远程的内容编码不同时使用。
案例代码:
$(function(){ $('#send').click(function(){ $.ajax({ type: "GET", url: "test.json", data: {username:$("#username").val(), content:$("#content").val()}, dataType: "json", success: function(data){ $('#resText').empty(); //清空resText里面的所有内容 var html = ''; $.each(data, function(commentIndex, comment){ html += '' + comment['username']+ ':+ ''; }); $('#resText').html(html); } }); }); });
顺便说一下$.each()函数:
$.each()函数不同于JQuery对象的each()方法,它是一个全局函数,不操作JQuery对象,而是以一个数组或者对象作为第1个参数,以一个回调函数作为第2个参数。回调函数拥有两个参数:第1个为对象的成员或数组的索引,第2个为对应变量或内容。
以上这篇jQuery Ajax 实例代码 ($.ajax、$.post、$.get)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。