My situation is, I’m developing a little web app where the server provides dynamic JSON responses. The server is built on cherrypy. Sometimes, there is a bug in the code creating the JSON data, which throws, and cherrypy catches it and serves back a 500-error with a full HTML page detailing the exception. (That is, the response has everything: <!doctype..><html><head>...</head><body>...</body></html>)
But because the request is AJAX, it doesn’t get displayed.
I can intercept this error easily enough, and look at it in the dev tools; but what I’d like to do (to ease debugging) is open a new page (as if user had followed a link) and display that response in the browser. I tried
window.open('', '_self');
$(document).html(jqXHR.responseText);
but I just get a blank page. I suppose I could store the error text and serve it up in a second request to the server, but is there a cleaner way?
To follow up, the final code that worked was this:
.error(function(jqXHR, textStatus, errorThrown) {
$(window).bind('unload', function() { document.write(jqXHR.responseText); } );
var win = window.open('', '_self');
return false;
});
Not sure if that final return false is necessary but it seems good form.
Following up again: the above code worked reliably in Opera. I thought I had seen it working in Webkit as well, but I started noticing that it wasn’t; and on further testing, it wasn’t working for Firefox either.
What I found that worked in all three platforms was this:
document.open('text/html', true);
document.write(jqXHR.responseText);
document.close();
Don’t have to open another window or bind events; just re-open the document and stuff the text in there.
Well, here I am again. The above technique either stopped working or I was tripping when I said it ever worked at all. Chrome, in particular, doesn’t seem to have document.open defined.
But! I just found a nifty technique that seems to work everywhere:
errtext = 'data:text/html;base64,' + window.btoa(jqXHR.responseText);
window.open(errtext, '_self');
This simply converts the response into a fully self-contained data: URL and opens it in the window.
Try this: