Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get 'getJSON' response header

I need to access the size of response message I am getting from another machine (cross-domain request) using $.getJSON, although I can see the request and response in chrome console, it does not work. Here is my request code:

xhr=$.getJSON('http://192.168.1.102/server/server.php?callback=?',   
{data:array}, function(res){
alert(xhr.getAllResponseHeader());
}, 
type='json'); 

when running I get "Uncaught TypeError: Object # has no method 'getAllResponseHeader' " error. When I use

alert(xhr.getResponseHeader("Content-Length"));

I get "null".

Please consider that I am using cross-domain get.

like image 565
Espanta Avatar asked Mar 13 '13 12:03

Espanta


2 Answers

Do not use JSONP, it isn't really a cross domain request (JSONP explained), it's a hack that only works for GET requests, whereas AJAX allows any http method.

Try preparing your server to allow cross domain requests (more details) and doing this:

$.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);
}});

Thereby, the xhr object is set and you can access it's header.

like image 91
vhtc Avatar answered Oct 06 '22 09:10

vhtc


Try this:

xhr=$.getJSON('http://192.168.1.102/server/server.php?callback=?',   
  {data:array}, function(res,status,xhr){
    alert(xhr.getAllResponseHeaders()); 
    // not getAllResponseHeader its only getResponseHeader
});

For cross domain use

$.ajax({
  url: 'http://192.168.1.102/server/server.php?callback=?',
  dataType: 'json',
  jsonpCallback: 'MyJSONPCallback', // specify the callback name if you're hard-coding it
  success: function(data){
    // we make a successful JSONP call!
  }
});

Refer this jQuery getJSON works locally, but not cross domain

Docs For getAllResponseHeaders, getResponseHeader and ajax http://api.jquery.com/jQuery.ajax/

like image 33
Rohan Kumar Avatar answered Oct 06 '22 09:10

Rohan Kumar