$.ajax({
url: '?', // 请求地址,缺省则为当前页面URL
dataType: 'json', // 服务器响应的数据类型,若不指定则自动根据HTTP包MIME信息来智能判断
type: 'POST', // 请求的类型,可选值:GET|POST,缺省则为GET
data: {
param1: '这是param1的值',
param2: '这是param2的值',
param3: '这是param3的值',
},
timeout: 1000 * 30, // 请求超时时间,单位:毫秒
cache: false, // 是否缓存此页面,缺省值为true
async: false, // 请求是否为异步请求,缺省值为true
processData: false, // 如有上传文件必须设置该参数为false
contentType: false, // 如有上传文件必须设置该参数为false
/**
* 发送请求前运行的函数
*
* @param object xhr XMLHttpRequest对象
*/
beforeSend: function (xhr) {
console.log(xhr);
},
/**
* 请求失败时运行的函数
*
* @param object xhr XMLHttpRequest对象
* @param null|string ts 错误类型,如果不为null则可能值有:timeout、error、abort、notmodified、parsererror
* @param string et 错误信息,如404错误的Not Found、500错误的Internal Server Error
*/
error: function (xhr, ts, et) {
if (ts == 'timeout') {
console.log('请求超时');
}
},
/**
* 请求成功时运行的函数
*
* @param object data 服务器返回的数据
* @param string ts 包含成功代码的textStatus字符串
*/
success: function (data, ts) {
console.log(data);
},
/**
* 请求完成时运行的函数
* 备注:该函数无论如何都会运行,且会在success()或error之后。
*
* @param object xhr XMLHttpRequest对象
* @param string ts 包含成功或错误代码的textStatus字符串
*/
complete: function (xhr, ts) {
if (ts == 'timeout') {
console.log('请求超时');
}
},
});
//========== 简化版 ==========//
$.ajax({
url: '?',
type: 'POST',
data: new FormData(),
processData: false,
contentType: false,
beforeSend: function () {},
success: function (response) {
console.log(response);
if (response.errcode == 0) {
// TODO...
} else {
alert(response.errmsg);
}
},
complete: function () {},
});
Copyright © 2025 码农人生. All Rights Reserved