jQuery.post()
使用一个HTTP POST 请求从服务器加载数据。
jQuery.post(url[, data ][, success ][, dataType ])
- url类型:String一个包含发送请求的URL字符串.
- data类型:PlainObject or String一个普通对象或字符串,通过请求发送给服务器。
- success类型:Function(PlainObject data, String textStatus, jqXHR jqXHR)当请求成功后执行的回调函数。如果提供
dataType选项,那么这个success选项是必须的,但这种情况下你可以使用null。 - dataType类型:String从服务器返回的预期的数据类型。默认:智能猜测(xml, json, script, text,html)。
jQuery.post([settings ])
- settings类型:PlainObject一组用于配置Ajax请求的键/值对。除了
url以外的所有选项属性都是可选的。任何默认选项可以用$.ajaxSetup()进行设置。所有选项设置的完整列表,请参阅jQuery.ajax(settings)。 type(类型)选项将自动设置为POST。
这是一个 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()是无效的。
The jqXHR Object(jqXHR 对象)
从jQuery 1.5开始,所有jQuery的Ajax方法都返回一个XMLHTTPRequest对象的超集。这个通过$.post()方法返回的jQuery XHR对象,或“jqXHR”,实现了 Promise 接口,使它拥有 Promise 的所有属性,方法和行为(见Deferred 对象获取更多信息)。jqXHR.done()(表示成功),jqXHR.fail()(表示错误),和jqXHR.always()(表示完成,无论是成功或错误;在jQuery 1.6 中添加)方法接受一个函数参数,用来请求终止时被调用。关于这个函数接收参数的详细信息,请参阅 jqXHR Object 文档中的$.ajax()章节。
Promise 接口也允许jQuery的Ajax方法,包括$.get(),在一个单独的请求中关联到.done(),.fail(),和.always()回调函数,甚至允许你在请求已经结束后,指派回调函数。如果该请求已经完成,则回调函数会被立刻调用。
// 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"); });
Deprecation Notice(推荐使用的注意事项:)
jqXHR.success(),jqXHR.error(),和jqXHR.complete()回调方法在jQuery 1.5中引进,在jQuery 1.8中不赞成使用,已经过时。他们最终将被取消(移除),你的代码应该为次做好准备,从jQuery 3.0开始被删除,你可以使用jqXHR.done(),jqXHR.fail(),和jqXHR.always()代替.
Additional Notes:(其他注意事项:)
- 由于浏览器的安全限制,大多数“Ajax”的要求,均采用同一起源的政策;即无法从不同的域,子域或协议中正确接收数据。
- 如果一个jQuery.post()请求返回一个错误代码,它会静静的失败,除非脚本调用全局的.ajaxError()方法。在jQuery 1.5,通过jQuery.post()返回的
jqXHR对象的.error()方法也可用于错误处理。
例子
请求 test.php 页面,但是忽略返回结果
$.post("test.php");
请求 test.php 页面并且发送url参数(虽然仍然忽视返回的结果)。
$.post("test.php", { name: "John", time: "2pm" } );
传递数组形式data参数给服务器(虽然仍然忽视返回的结果)。
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
使用Ajax请求发送表单数据。
$.post("test.php", $("#testform").serialize());
Alert 从 test.php请求的数据结果(HTML 或者 XML,取决于返回的结果)。
$.post("test.php", function (data) {
alert("Data Loaded: " + data);
});
Alert 从 test.cgi请求并且发送url参数的数据结果(HTML 或者 XML,取决于返回的结果)。
$.post("test.php", { name: "John", time: "2pm" },
function (data) {
alert("Data Loaded: " + data);
});
得到test.php的内容,存储在一个 XMLHttpResponse 对象中并且运用 process()JavaScript函数。
$.post("test.php", { name: "John", time: "2pm" },
function (data) {
process(data);
},
"xml"
);
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){
console.log(data.name); // John
console.log(data.time); // 2pm
}, "json");
用ajax传递一个表单并把结果在一个div中
<!DOCTYPE html>
<html>
<head>
<script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
</head>
<body>
<form action="/" id="searchForm">
<input type="text" name="s" placeholder="Search..." />
<input type="submit" value="Search" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
/* attach a submit handler to the form */
$("#searchForm").submit(function (event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
term = $form.find( 'input[name="s"]' ).val(),
url = $form.attr( 'action' );
/* Send the data using post and put the results in a div */
$.post( url, { s: term },
function ( data ) {
var content = $( data ).find( '#content' );
$( "#result" ).empty().append( content );
}
);
});
</script>
</body>
</html>
