简单示例
$.ajax({
url: '请求路径', //如:localhost:8080/demo/test
type: 'POST', //GET/post
async: true, //或false,是否异步
data: {}, //请求参数
timeout: 5000, //超时时间
dataType: 'json', //返回的数据格式:json/xml/html/script/jsonp/text
beforeSend: function(xhr) {
console.log(xhr)
console.log('发送前')
},
success: function(data, textStatus, jqXHR) {
//处理data
console.log(data)
console.log(textStatus)
console.log(jqXHR)
},
error: function(xhr, textStatus) {
console.log('错误')
console.log(xhr)
console.log(textStatus)
},
complete: function() {
console.log('结束')
}
});
参数
options
类型:Object
可选。AJAX 请求设置。所有选项都是可选的。
async
类型:Boolean
默认值: true。默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。
注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
beforeSend(XHR)
类型:Function
发送请求前可修改 XMLHttpRequest 对象的函数,如添加自定义 HTTP 头。
XMLHttpRequest 对象是唯一的参数。
这是一个 Ajax 事件。如果返回 false 可以取消本次 ajax 请求。
cache
类型:Boolean
默认值: true,dataType 为 script 和 jsonp 时默认为 false。设置为 false 将不缓存此页面。
jQuery 1.2 新功能。
complete(XHR, TS)
类型:Function
请求完成后回调函数 (请求成功或失败之后均调用)。
参数: XMLHttpRequest 对象和一个描述请求类型的字符串。
这是一个 Ajax 事件。
contentType
类型:String
默认值: “application/x-www-form-urlencoded”。发送信息至服务器时内容编码类型。
默认值适合大多数情况。如果你明确地传递了一个 content-type 给 $.ajax() 那么它必定会发送给服务器(即使没有数据要发送)。