Thursday, March 3, 2011

Can I trigger a complete web page reload with content from a javascript string ?

This is one of those ajax "alternate flow" questions. Normally I expect my ajax request to return a part of the page. But sometimes it may return a full page with html, head and body tag.

At the time I return from my ajax-request I can detect if this is a full page, but is it possible to trigger a full page reload (with full event cycle) based on the string content I have ?

(And yes, I have tried replacing the body element, but that does not give me the events and does not allow me to change the content in the head block)

Any framework reference is ok

From stackoverflow
  • I don't think it's possible to do directly.

    You'd be better off saving the HTML somewhere and sending back a URL where it can be retrieved, then using location.href = ...;

  • At least in Firefox, you can use the window.location property. The location object contains information about the URL of the document and provides methods for changing that URL. You can also assign to this property to load another URL.

    An example from the doc:

    Replace the current document with the one at the given URL:
    
    function goMoz() { 
       window.location = "http://www.mozilla.org";
    } 
    
    // in html: <button onclick="goMoz();">Mozilla</button>
    
  • You can decide what to do with your AJAX request based on it's HTTP status code.

    If you get 301 ("moved permanently") you could do a redirect using window.location:

    new Ajax.Request(url, {
      method: 'get',
      // status 200: yadaa
      onSuccess: function(transport) {
        // doSomething
      },
      // status 301: moved permanently
      on301: function(transport){ 
        window.location = transport.responseText;
      }
    });
    
    krosenvold : This sounds good, especially if I use an additional header field in the 302 to indicate full page redirect.
    krosenvold : Unfortunately this does not seem to work, since 301/302 does not seem to reach prototype (its handled by the browser and never reaches javascript).
  • window.location = "same-url-as-im-at.aspx";

    ...?

    To do it with an HTML document directly I'd desperately try to avoid if I were you for reasons you have skimmed in your original question...

0 comments:

Post a Comment