最近搜索

封装post 请求 加上token

浏览:22
管理员 2025-10-10 14:53

html页面请求 加上token

post 请求 加上token   

headers  请求 加上token     

headers.token



/**

 * 封装带token认证的POST请求

 * @param {string} url - 请求地址

 * @param {Object} data - 请求参数对象

 * @param {string} [token] - 认证token(可选)

 * @param {Function} [success] - 成功回调函数

 * @param {Function} [error] - 失败回调函数

 */

function postWithToken(url, data, token, success, error) {

    $.ajax({

        url: url,

        type: "POST",

        headers: {

            "Authorization": "Bearer " + (token || '') // 支持token参数传递

        },

        data: data,

        success: success,

        error: error

    });

}





// 从缓存获取token

var token = localStorage.getItem('auth_token');


// 调用封装方法

postWithToken(

    'https://api.example.com/save', 

    {

        title: '示例标题',

        jifen: 100,

        // 其他参数...

    },

    token,

    function(result) {

        // 成功处理逻辑

        console.log(result);

    },

    function(xhr, status, error) {

        // 失败处理逻辑

        console.error(error);

    }

);





postWithToken(

    'https://api.example.com/save',

    {

        title: '示例标题',

        jifen: 100

    },

    token

).done(function(result) {

    // 成功处理

}).fail(function(xhr) {

    // 失败处理

});


联系站长

站长微信:xiaomao0055

站长QQ:14496453