我需要使用 $.getJSON 访问我从另一台机器(跨域请求)获得的响应消息的大小,虽然我可以在 chrome 控制台中看到请求和响应,但它不起作用。这是我的请求代码:
xhr=$.getJSON('http://192.168.1.102/server/server.php?callback=?',
{data:array}, function(res){
alert(xhr.getAllResponseHeader());
},
type='json');
运行时出现“Uncaught TypeError: Object # has no method 'getAllResponseHeader'”错误。当我使用
alert(xhr.getResponseHeader("Content-Length"));
我得到“空”。
请考虑我正在使用跨域获取。
最佳答案
不要使用 JSONP,它不是真正的跨域请求 ( JSONP explained ),它是一种仅适用于 GET 请求的 hack,而 AJAX 允许任何 http 方法。
尝试准备您的服务器以允许跨域请求(more details)并执行此操作:
$.ajax({
type: "get",
url: "http://192.168.1.102/server/server.php",
crossDomain: true,
cache: false,
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: array,
success: function(data, textStatus, xhr) {
console.log(data);
console.log(xhr.getResponseHeader("Content-Length"));
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}});
由此,设置了 xhr 对象,您可以访问它的 header 。
关于javascript - 如何获取 'getJSON' 响应头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15385514/