Home > Web Front-end > JS Tutorial > body text

Summary of usage of $.post and $.ajax in Jquery

PHPz
Release: 2018-10-15 15:23:58
Original
1146 people have browsed it

Usage of Jquery's $.ajax:

jQuery.ajax( options ): Load remote data through HTTP requests. This 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 will not need to manipulate this object directly, but in special cases it can be used to manually terminate the request.

Note: If you specify the dataType option, make sure the server returns the correct MIME information (e.g. xml returns "text/xml"). Incorrect MIME types can cause unpredictable errors. See Specifying the Data Type for AJAX Requests.

When the datatype is set to 'script', all remote (not in the same domain) POST requests will be converted to GET.

$.ajax() has only one parameter: parameter key/value object, including each configuration and callback function information. See detailed parameter options below.

In jQuery 1.2, you can load JSON data across domains. When using it, you need to set the data type to JSONP. 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. When the data type is set to "jsonp", jQuery will automatically call the callback function. (I don’t understand this very well)

jquery ajax parameter list:

url(String)

(Default: current page address) The address to send the request.

type(String)
Request method (there are two parameters: "POST" and "GET"), the 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 (milliseconds). This setting overrides the global setting.

async(Boolean)

(Default: true) When set to true, 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)

You can modify the functions of the XMLHttpRequest object before sending the request, such as adding custom HTTP headers. The XMLHttpRequest object is the only parameter.

The code is as follows:
function(XMLHttpRequest){ this; // the options for this ajax request}
cache(Boolean)
Copy after login

Whether to cache the request results (default: true) , setting it to false will not load the request information from the browser cache. Note that it is best to set it to false in the early stages of development, otherwise it will be inconvenient to debug.

complete(Function)

Callback function after the request is completed (called when the request succeeds or fails). Parameters: XMLHttpRequest object, success information string.

The code is as follows:
function(XMLHttpRequest,textStatus){
 this;//theoptionsforthisajaxrequest
}
Copy after login

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

Define the data type 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 XML format data, which can be processed by jQuery.
"html": Returns plain text HTML format data; can contain 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: automatic judgment (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.

The code is as follows

function(XMLHttpRequest,textStatus,errorThrown){
 //通常情况下textStatus和errorThown只有其中一个有值
 this;//theoptionsforthisajaxrequest
}
Copy after login

global(Boolean)

是否触发全局 AJAX 事件(默认: true) 。设置为 false 将不会触发全局 AJAX 事件,如 ajaxStart 或 ajaxStop 。可用于控制不同的Ajax事件

ifModified(Boolean)

(默认: false) 仅在服务器数据改变时获取新数据。使用 HTTP 包 Last-Modified 头信息判断。

processData(Boolean)

设置发送数据的信息格式(默认: true),设置为 true 的时候发送的数据将被转换为对象(技术上讲并非字符串) 以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。

success(Function)

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

代码如下:

function(data,textStatus){ 
 //datacouldbexmlDoc,jsonObj,html,text,etc... 
 this;//theoptionsforthisajaxrequest 
}
Copy after login

下面以一则示例解释一下该方法的具体的用法:

$.ajax({ 
  type:'get', 
  url:'http://www.www.daimajiayuan.com/rss', 
  beforeSend:function(XMLHttpRequest){ 
    //ShowLoading(); 
  }, 
  success:function(data,textStatus){ 
    $('.ajax.ajaxResult').html(''); 
    $('item',data).each(function(i,domEle){ 
      $('.ajax.ajaxResult').append(''+$(domEle).children('title').text()+''); 
    }); 
  }, 
  complete:function(XMLHttpRequest,textStatus){ 
    //HideLoading(); 
  }, 
  error:function(){ 
    //请求出错处理 
  } 
});
Copy after login

Jquery的$.post的用法:

3. jQuery.post( url, [data], [callback], [type] ) :使用POST方式来进行异步请求
jquery $.post 方法参数列表(说明):
url (String) : 发送请求的URL地址.
data (Map) : (可选) 要发送给服务器的数据,以 Key/value 的键值对形式表示,可将此值放到url中。
callback (Function) : (可选) 载入成功时回调函数(只有当Response的返回状态是success才能调用该方法)。

type (String) : (可选)客户端请求的数据类型(JSON,XML,等等)

这是一个简单的 POST 请求功能以取代复杂 $.ajax ,请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax。
下面是一个使用$.post的简单示例代码:

$.post( 
  'http://www.daimajiayuan.com/ajax.php', 
  {Action:"post",Name:"lulu"}, 
  function(data,textStatus){ 
    //data可以是xmlDoc,jsonObj,html,text,等等. 
    //this;//这个Ajax请求的选项配置信息,请参考jQuery.get()说到的this 
    alert(data.result); 
  }, 
  "json"//这里设置了请求的返回格式为"json" 
);
Copy after login

如果你设置了请求的格式为"json",此时你没有设置Response回来的ContentType 为:Response.ContentType = "application/json"; 那么你将无法捕捉到返回的数据。

注意,上面的示例中 alert(data.result); 由于设置了Accept报头为"json",这里返回的data就是一个对象,因此不需要用eval()来转换为对象。

以上所述就是本文的全部内容了,希望大家能够喜欢。

【相关教程推荐】

1. JavaScript视频教程
2. JavaScript在线手册
3. bootstrap教程

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