📅  最后修改于: 2023-12-03 15:32:08.148000             🧑  作者: Mango
jQuery ajax()方法是一种基于JavaScript的异步请求方法,它可以通过HTTP请求在后台发送和接收数据,并且不会阻塞用户对页面的操作。
$.ajax({
url: "test.html",
method: "GET",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
})
.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
$.ajax({
url: "test.html",
method: "GET",
data: { name: "John", location: "Boston" },
dataType: "json"
})
.done(function( data ) {
console.log( "Data Received: ", data );
})
.fail(function( jqXHR, textStatus ) {
console.error( "Request failed: ", textStatus );
});
$.ajax({
url: "test.php",
method: "POST",
data: { name: "John", location: "Boston" },
dataType: "json"
})
.done(function( data ) {
console.log( "Data Received: ", data );
})
.fail(function( jqXHR, textStatus ) {
console.error( "Request failed: ", textStatus );
});
通过ajax()方法,我们可以轻松地发送各种类型的HTTP请求,并且在请求完成后执行相应的回调函数,从而实现异步操作。当然,为了确保页面能够正常显示,我们需要注意请求的异步性和请求结果的缓存性。