Home > Web Front-end > JS Tutorial > Talk about jQuery Ajax usage details_jquery

Talk about jQuery Ajax usage details_jquery

WBOY
Release: 2016-05-16 15:29:30
Original
1400 people have browsed it

Definition and usage

The ajax() method loads remote data through HTTP requests.

This method is the underlying AJAX implementation of jQuery. For simple and easy-to-use high-level implementations, see $.get, $.post, etc. $.ajax() returns the XMLHttpRequest object it created. In most cases you won't need to manipulate this function directly unless you need to manipulate less commonly used options for more flexibility.

In the simplest case, $.ajax() can be used directly without any parameters.

Note: All options can be set globally through the $.ajaxSetup() function.

jQuery Ajax is very commonly used in web application development. It mainly includes common refresh-free operation methods such as ajax, get, post, load, getscript, etc. Let me introduce it to you.

Let’s start with the simplest method. When processing complex ajax requests, jQuery uses the jQuery.ajax() method. There are some simple methods in jQuery, which encapsulate the jQuery.ajax() method, so that we do not need to use the jQuery.ajax() method when handling some simple Ajax events. Some of these methods are in previous articles. It has already appeared, I believe everyone will be able to master it soon. Of course, the jQuery.ajax() method will be explained very specifically in the second half of this article, because it is the top priority of this article.

The following 5 methods perform short forms of general Ajax requests. jQuery.ajax() should be used when handling complex Ajax requests.

1.load(url,[data],[callback])

Load the remote HTML file code and insert it into the DOM. The GET method is used by default, and it is automatically converted to the POST method when passing parameters.

◦url: the remote url address to be loaded
◦data: key/value data sent to the server
◦callback: callback function when loading is successful

The sample code is as follows:

//无参数、无回调函数
$("#showload").load("load.htm");
//无回调函数
$("#showload").load("load.htm", { "para": "para-value" });
$("#showload").load("load.htm", { "para": "para-value" },
 function() {
  //处理
 })
Copy after login

The content of the loaded file will be displayed here Load

2.jQuery.get(url, [data], [callback])

Use the get method to obtain data from the server.

◦ URL address to send request
◦Data to be sent to the server
◦Callback function when loading is successful

The sample code is as follows:

$.get("jqueryget.htm", { "id": this.id },
 function(req) {
  //成功时的回调方法
  $("#showget").html(req);
 });
})
Copy after login

Use the $.get() method to get different logos by passing the id. It is worth mentioning that the request is obtained through the get method at this time, so Request.QueryString must be used when obtaining parameter values. You can take a look at the difference between Request Request.QueryString

Baidu logo Google logo

logo3.jQuery.post(url, [data], [callback])
will be displayed here Use POST method to make asynchronous requests. Compared with jQuery.get(), the difference lies in the request method, so there is no special explanation here. The usage method is similar to jQuery.get().

4.jQuery.getScript(url,[callback])

Request to load and execute a JavaScript file through GET method. This technology has been mentioned in the previous article, and it is also a simple way to use jQuery.ajax. You can see ajax loading js, so there is no special explanation here.

5.jQuery.getJSON(url,[data],[callback])

Get data in json format through get method.

The sample code is as follows:

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(req) {
 $.each(req.items, function(i, item) {
  if (i == vnum) {
   $("<img src="" + item.media.m + "" title="" + item.title + "" />").appendTo("#showjson");
  }
 });
});
Copy after login

Similarly, this is also a shorthand method for the jQuery.ajax() method, similar to the following method:

Parameter list:

Parameter name Type Description
url String (Default: current page address) The address to send the request.
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 request timeout (milliseconds). This setting overrides the global setting.
async Boolean (Default: true) By default, all requests are asynchronous requests. If you need to send synchronous requests, set this option to false. Note that a synchronous request will lock the browser, and the user must wait for the request to complete before other operations can be performed.
beforeSend Function The functions of the XMLHttpRequest object can be modified before sending the request, such as adding custom HTTP headers. The XMLHttpRequest object is the only parameter.
<span style="color: rgb(0,0,255)">function (XMLHttpRequest) { <span style="color: rgb(0,0,255)">this; <span style="color: rgb(0,128,0)">// the options for this ajax <a target="_blank" style="color: rgb(51,153,255); text-decoration: none" href="http://www.php100.com/tags.php/request/">request</a>}</span></span></span>
Copy after login
cache Boolean (默认: true) jQuery 1.2 新功能,设置为 false 将不会从浏览器缓存中加载请求信息。
complete Function 请求完成后回调函数 (请求成功或失败时均调用)。参数: XMLHttpRequest 对象,成功信息字符串。
<span style="color: rgb(0,0,255)">function (XMLHttpRequest, textStatus) { <span style="color: rgb(0,0,255)">this; <span style="color: rgb(0,128,0)">// the options for this ajax request}</span></span></span>
Copy after login
contentType String (默认: "application/x-www-form-urlencoded") 发送信息至服务器时内容编码类型。默认值适合大多数应用场合。
data Object,
String
Data sent to the server. Will be automatically converted to request string format. 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 the same name to different values. For example, {foo:["bar1", "bar2"]} is converted to '&foo=bar1&foo=bar2'.
dataType String

The data type expected to be returned by the server. If not specified, jQuery will automatically return responseXML or responseText based on the HTTP packet MIME information and pass it as a callback function parameter. Available values:

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

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

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

"json": Returns JSON data.

"jsonp": JSONP format. When calling a function using JSONP format, such as "myurl?callback=?" jQuery will automatically replace ? with the correct function name to execute the callback function.

error Function (Default: Automatically determine (xml or html)) This method will be called when the request fails. This method takes three parameters: the XMLHttpRequest object, the error message, and (possibly) the captured error object.
<span style="color: rgb(0,0,255)">function (XMLHttpRequest, textStatus, errorThrown) { <span style="color: rgb(0,128,0)">// 通常情况下textStatus和errorThown只有其中一个有值 <span style="color: rgb(0,0,255)">this; <span style="color: rgb(0,128,0)">// the options for this ajax request}</span></span></span></span>
Copy after login
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 请求成功后回调函数。这个方法有两个参数:服务器返回数据,返回状态
<span style="color: rgb(0,0,255)">function (data, textStatus) { <span style="color: rgb(0,128,0)">// data could be xmlDoc, jsonObj, html, text, etc... <span style="color: rgb(0,0,255)">this; <span style="color: rgb(0,128,0)">// the options for this ajax request}</span></span></span></span>
Copy after login

这里有几个Ajax事件参数:beforeSend ,success ,complete ,error 。我们可以定义这些事件来很好的处理我们的每一次的Ajax请求。注意一下,这些Ajax事件里面的 this 都是指向Ajax请求的选项信息的(请参考说 get() 方法时的this的图片)。

代码如下

$.ajax({
 url: url,
 dataType: 'json',
 data: data,
 success: callback
});
Copy after login

可能你还没有使用过json数据,我的小站中已经好几次提到了json的使用,如果你还不熟悉json格式,可以看看jquery移动listbox的值、jQuery下json的使用实例

获得json数据

这 里将随机显示一条json数据到目前为止我们总结了jQuery.ajax的五种简写方法,接下来让我们集中精神,看看jQuery.ajax()方法, 在使用中,笔者也是经常使用的jQuery.ajax(),因为大多数情况,我们需要对ajax请求出错的情况进行捕捉并处理。

6.jQuery.ajax()

使用jQuery.ajax()方法获取数据,下边给个常用写法,并做了相应的注释。

代码如下

$.ajax({
 url: "http://www.hzhuti.com", //请求的url地址
 dataType: "json", //返回格式为json
 async: true, //请求是否异步,默认为异步,这也是ajax重要特性
 data: { "id": "value" }, //参数值
 type: "GET", //请求方式
 beforeSend: function() {
  //请求前的处理
 },
 success: function(req) {
  //请求成功时处理
 },
 complete: function() {
  //请求完成的处理
 },
 error: function() {
  //请求出错处理
 }
});
Copy after login

使用jQuery.ajax()

这里将显示数据

$.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("异常!"); 
  } 
});
Copy after login
//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&#63;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); 
 }
});
Copy after login

本篇的jQuery ajax使用就总结到这里,当然还有一些方法并未能全部的总结。如ajaxStart()、ajaxStop()等,在以后使用中,我会把它们也总结下来。

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