首页 > 解决方案 > 在 chrome 开发工具的“响应”选项卡中有可用数据时,在 AJAX 响应中获取“未定义”

问题描述

我正在尝试从以下跨域 ajax 请求中获取响应,但未成功定义:

$.ajax({
            type: "GET",
            url: "https://path_to_app/rest/jjwt",
            crossDomain: true,
            dataType: 'script',
            contentType: 'text/plain;charset=UTF-8',
            beforeSend: function(xhr) {
                xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
                xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
            },
            success: function (response, textStatus, xhr) {
                console.log(response);
                console.log(textStatus);
            },
            error: function (jqXHR, exception) {
                var msg = '';
                if (jqXHR.status === 0) {
                    msg = 'Not connect.\n Verify Network.';
                } else if (jqXHR.status == 404) {
                    msg = 'Requested page not found. [404]';
                } else if (jqXHR.status == 500) {
                    msg = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
                    msg = 'Requested JSON parse failed.';
                } else if (exception === 'timeout') {
                    msg = 'Time out error.';
                } else if (exception === 'abort') {
                    msg = 'Ajax request aborted.';
                } else {
                    msg = 'Uncaught Error.\n' + jqXHR.responseText;
                }
                console.log(msg);
            }
        });

请参阅以下开发工具中的响应: 在此处输入图像描述

当尝试在浏览器中使用完全相同的 url 时,我可以在授权后看到预期的响应(令牌): 服务器响应

标签: javascriptjqueryajaxgetcors

解决方案


推荐阅读