【发布时间】:2015-10-23 08:08:04
【问题描述】:
我设法使用jQuery.ajax() 获取 JSON 内容。目前,它从包含单个 index.php 文件的另一个主机获取内容,该文件返回 401 响应,正文如下:{'status':401}。
这是JS:
$(document).ready(function() {
$.ajax({
url: 'http://restapi',
type: 'GET',
dataType: 'json',
success: function() { document.write('works'); },
error: function(xhr) { document.write('failed, status:' + xhr.status); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer 12345');
}
还有 PHP:
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header('Access-Control-Allow-Credentials: true');
header("Access-Control-Allow-Headers: X-Requested-With, Authorization");
header("HTTP/1.1 401 Unauthorized");
echo json_encode(['status' => 401]);
exit;
如果我删除标题 xhr.setRequestHeader('Authorization', 'Bearer 12345');,一切正常(响应有一个 json 正文,xhr.status 返回 401)。但是使用 Authorization 标头时,正文不会返回任何内容,xhr.status 会返回 0。
我需要在该标头中发送身份验证令牌。
【问题讨论】:
标签: javascript php jquery ajax http-headers