jQuery.post()
函数用于通过HTTP POST形式的AJAX请求获取远程数据。
jQuery.post()
函数用于实现简单的POST形式的Ajax请求,它在底层是使用jQuery.ajax()来实现的,只是省略了大多数不常用的参数设置,并仅限于HTTP POST方式。
请注意,该函数是通过异步方式加载数据的。
该函数属于全局jQuery
对象。
jQuery 1.0 新增该静态函数。
jQuery.post( url [, data ] [, success ] [, type ] )
参数 | 描述 |
---|---|
url | String类型指定请求的目标URL。 |
data | 可选/String/Object类型发送请求传递的数据。 |
success | 可选/Function类型请求成功时执行的回调函数。它有3个参数:其一是请求返回的数据,其二是请求状态文本(例如"success"、 "notmodified"),其三是当前jqXHR对象(jQuery 1.4及之前版本,该参数为原生的XMLHttpRequest对象)。 |
type | 可选/String类型指定请求返回的数据类型,可以为xml、 html、 script、 json、 jsonp、text。如果省略该参数,jQuery将会根据请求进行智能猜测,猜测范围为:xml、 json、 script或html。 |
关于参数type
的值所表示的含义,请参考jQuery.ajax()中的可选参数dataType。
参数success
指定的回调函数只有在请求成功时才会执行,如果请求失败(例如找不到页面、服务器错误等)则不作任何处理。
jQuery.post()
函数的返回值为jqXHR类型,返回发送该请求的jqXHR对象(jQuery 1.4及之前版本,返回的是原生的XMLHttpRequest对象)。
jqXHR
对象是经过jQuery封装的类XMLHttpRequest对象。
jQuery.post()
是jQuery.ajax()
函数的如下简写形式:
jQuery.post(url, data, success, dataType); // 等价于 $.ajax({ url: url, type: "POST", data: data, success: success, dataType: dataType });
请参考以下这段HTML示例代码:
<div id="content1">CodePlayer</div> <div id="content2">专注于编程开发技术分享</div> <div id="content3">http://www.365mini.com</div>
以下是与jQuery.post()
函数相关的jQuery示例代码,以演示jQuery.post()
函数的具体用法:
// 以POST请求方式获取http://localhost/index.php?id=5的数据,但不作任何处理 $.post( "http://localhost/index.php?id=5" ); // 等价于 http://localhost/index.php?id=5&orderId=5&money=100 $.post( "http://localhost/index.php?id=5", "orderId=5&money=100" ); // 等价于 http://localhost/index.php?id=5&orderId=5&money=100 $.post( "http://localhost/index.php?id=5", {orderId: 5, money: 100} ); /* ***** 一般不会使用上述不对获取的POST数据作任何处理的用法***** */ // 以POST请求方式获取http://localhost/index.php?id=5的数据,将返回的html内容追加到body标签内 $.post( "http://localhost/index.php?id=5", function(data, textStatus, jqXHR){ // data 是该请求返回的数据(可能经过处理) // textStatus 可能是"success"、 "notmodified"等 // jqXHR 是经过jQuery封装的XMLHttpRequest对象(保留其本身的所有属性和方法) $("body").append( data ); } ); $.post( "http://localhost/index.php?id=5", { bookId: 2 }, function(data, textStatus, jqXHR){ // 如果返回的原始文本数据为{ "name": "CodePlayer", "age": 20 } // 由于post()指定了返回数据的类型为JSON,则jQuery将会尝试将返回数据转换为JSON对象 // 如果转换成功,这里的data就已经是一个js对象 alert( data.name ); // CodePlayer }, "json" );