How to display error (text / html) on an AJAX / getJSON request?

My situation is that I am developing a small web application where the server provides dynamic JSON responses. The server is built on cherry. Sometimes an error occurs in the code that creates the JSON data, which throws, and cherrypy catches it and returns a 500 error with a full HTML page with a detailed description of the exception. (That is, the answer has everything: <!doctype..><html><head>...</head><body>...</body></html> ) But since the AJAX request, it does not appear .

I can easily catch this error and look at it in dev tools; but what I would like to do (to facilitate debugging) opens a new page (as if the user was following the link) and displayed this answer 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 in a second request to the server, but is there a cleaner way?


To keep track, the last code processed was as follows:

 .error(function(jqXHR, textStatus, errorThrown) { $(window).bind('unload', function() { document.write(jqXHR.responseText); } ); var win = window.open('', '_self'); return false; }); 

Not sure if this final return false necessary, but seems like a good form.


Forward: The above code worked reliably in Opera. I thought I saw how it works in Webkit, but I began to notice that it wasn’t; and with further testing it also did not work in Firefox.

What I found that worked on all three platforms was as follows:

 document.open('text/html', true); document.write(jqXHR.responseText); document.close(); 

No need to open another window or bind events; just reopen the document and enter the text there.


Well, here I go again. The above technique either stopped working, or I turned off when I said that I had ever worked. Chrome, in particular, does not have document.open .

But! I just found a great way that seems to work all over the place:

 errtext = 'data:text/html;base64,' + window.btoa(jqXHR.responseText); window.open(errtext, '_self'); 

This simply converts the response into a fully autonomous data: URL and opens it in a window.

+6
source share
1 answer

Try the following:

 var win = window.open('', '_self'); win.document.getElementsByTagName('Body')[0].innerText = jqXHR.responseText; 
+1
source

Source: https://habr.com/ru/post/891777/


All Articles