2

I want to be able to read the response headers of my app with jquery, specifically, I set the header 'X-Messages' to a string representation of rail's flash messages hash.

My question is similar to this one: https://stackoverflow.com/a/2729454/103739

I have one major difference however, that this isn't a JSON response. I just want to read the headers returned in my HTML page with jQuery, and log something for each item in the JSON object.

Here is what I'm doing in my controller:

class ApplicationController < ActionController::Base
  after_filter :flash_to_headers

  # ...

  def flash_to_headers
    response.headers['X-Messages'] = flash.to_hash.to_json.to_s
  end
end

Then here is where I'm stumped, I want to get this JSON object in when the page loads and just display say a regular alert, or console.log:

$(document).ready(function() {
  var messages = document.getResponseHeader('X-Messages');
  console.log(messages);
});

Okay, now obviously getResponseHeader(), is not a function on document, but how can I accomplish this?

Community
  • 1
  • 1
JP Silvashy
  • 46,977
  • 48
  • 149
  • 227

2 Answers2

2

HTML DOM is designed to access and manipulate HTML documents.

HTTP header exists in HTTP protocol, not HTML document.

I don't think you can get HTTP header from a HTML DOM, because you can get a HTML DOM by FTP or other methods, how did you get HTTP header from FTP?

If you got to get this header, you have to use an ajax call to get it.

However, there is an exception:If you are writing a chrome (or other browser) extension, you can get headers from chrome API.

Li-chih Wu
  • 1,002
  • 1
  • 11
  • 19
2

You can get it using an Ajax call like this:

var xhr = $.ajax({
        type: "POST",
        data: {},
        url: "yoururl.html",
        success: function(output, status) {
            var messages = $.parseJSON(xhr.getResponseHeader('X-Messages'));
            console.log(messages);
        },
        error: function(output) {
            console.log(output);
        }
    });
palaѕн
  • 72,112
  • 17
  • 116
  • 136
  • While this is a great answer, I'm weary of having to make another ajax request, and it seems that what I really want to so it actually not possible. I think it's loosely related to the separation of the BOM and the DOM, but I'm not entirely sure. Thanks for your answer! – JP Silvashy Dec 22 '12 at 04:30