首页 > 解决方案 > 为什么我的标头没有使用 beforSend 方法设置?

问题描述

我正在尝试使用那段代码发出 ajax 请求:(我在 html 中加载的单独文件)

$(document).ready(function () {

    $('#loadDeviceBtn').click(function (event) {
        event.preventDefault();

        createTableIfNotExist();

        var device = $('#devices-search').val();
        console.log(device);

        getTopicsForDevice(device);
    });

});

function createTableIfNotExist() {
    if (!$('#table').length) {
        $('.card-body').append("<div id=\"table\"><table><thead><tr><th>Topic</th><th>Value</th></tr></thead></table></div>");
    }
}

function getTopicsForDevice(device) {
    $.ajax({
        type:"GET",
        url:"api_url",
        dataType: "json",
        beforeSend: function (request, settings) {
            console.log(settings.url);
            request.setRequestHeader("Authorization", "Bearer reallylongtoken");
        }
    });
}

但是我不断收到 403 错误,当我查看请求标头时,我尝试设置的授权不存在。但我知道该函数被调用是因为出现了日志。

可能很重要的小细节......我的 IDE(IntelliJ)没有将 ajax 字涂成黄色,而 beforeSend 字也没有像在其他工作项目中那样使用。

标签: javascriptjqueryhtmlajax

解决方案


推荐阅读