jQuery.post()
jQuery.post( url, [ data ], [ success(data, textStatus, jqXHR) ], [ dataType ] ) 返回: jqXHR
描述: 通过服务器HTTP POST请求加载数据
-
version added: 1.0jQuery.post( url, [ data ], [ success(data, textStatus, jqXHR) ], [ dataType ] )
url一个包含发送请求的URL字符串
data向服务器发送请求的对象或者字符串参数
success(data, textStatus, jqXHR)当请求成功后执行的回调函数。
dataType从服务器返回的预期的数据类型。默认:智能猜测(xml, json, script, or html)。
这是一个快速的AJax处理函数,相当于:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
success的回调函数是根据MIME类型的响应,通过返回的数据包括XML根节点, 字符串, JavaScript 文件, 或者 JSON 对象,。 它也通过了响应文本状态。
在jQuery 1.5,在success回调函数还通过了“jqXHR”对象 ( 在 jQuery 1.4中 ,它是通过XMLHttpRequest对象)。
大多数实现将指定一个成功的处理函数:
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
这个例子所请求的全部HTML代码片段插在页面。
用 POST 获取的页面是从来不缓存的, 所以这些请求中的 cache 和 ifModified 选项在 jQuery.ajaxSetup() 是没有效果的。
jqXHR 对象
在jQuery 1.5,所有jQuery的Ajax方法都返回的超集XMLHTTPRequest对象。这个jQuery XHR对象,或“jqXHR,”通过$.post()约定的接口实现返回,给它的所有属性,方法和约定的行为(见Deferred object获取更多信息)。为了方便和一致性,回调名称使用$.ajax(),它提供.error() .success()和.complete()方法。这些方法当$.ajax()请求终止时需要一个函数参数调用,这个函数接收$.ajax()回调函数名相同的参数。
在jQuery 1.5的约定接口也使jQuery的Ajax方法,其中包括$.post() ,以链多个.success(), .complete()和.error()回调的一个请求,甚至回调后分配这些请求可能已经完成。如果请求已经完成,立即触发回调。
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post("example.php", function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
// perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });
其他注意事项:
- 由于浏览器的安全限制,大多数“Ajax”的要求,均采用同一起源的政策 ;该请求不能成功地检索来自不同的域,子域或协议的数据。
- 如果一个jQuery.post()请求返回一个错误代码,它会静静的失败,除非脚本调用全局的.ajaxError()方法。在jQuery 1.5, 通过jQuery.get()返回的
.error()方法的jqXHR对象也可用于处理错误。
Examples:
Example: 请求 test.php 页面, 但是忽略返回结果
$.post("test.php");
Example: 请求 test.php 页面 并且发送url参数(虽然仍然忽视返回的结果)。
$.post("test.php", { name: "John", time: "2pm" } );
Example: 传递数组形式data参数给服务器 (虽然仍然忽视返回的结果)。
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
Example: 使用Ajax请求发送表单数据。
$.post("test.php", $("#testform").serialize());
Example: Alert 从 test.php请求的数据结果 (HTML 或者 XML,取决于返回的结果)。
$.post("test.php", function(data) {
alert("Data Loaded: " + data);
});
Example: Alert 从 test.cgi请求并且发送url参数的数据结果 (HTML 或者 XML,取决于返回的结果)。
$.post("test.php", { name: "John", time: "2pm" },
function(data) {
alert("Data Loaded: " + data);
});
Example: 得到test.php的内容,存储在一个 XMLHttpResponse 对象中并且运用 process() JavaScript函数。
$.post("test.php", { name: "John", time: "2pm" },
function(data) {
process(data);
},
"xml"
);
Example: Posts to the test.php page and gets contents which has been returned in json format (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>).
$.post("test.php", { "func": "getNameAndTime" },
function(data){
alert(data.name); // John
console.log(data.time); // 2pm
}, "json");