Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading non-HTML content with Javascript. Is it possible?

Here's the scenario:

I want to make some HTTP API calls using Javascript, and have the response load in the browser. The requests might be GET, POST, PUT or DELETE, and the response that comes back could be any type of content - it might be HTML, JSON, XML, or an images, document, binary content, or whatever. I'd like the response to be handled by the browser in exactly the same way as it would if the browser was loading a new page.

The problem is that I can't see any way to load the arbitrary content that I receive.

Obviously it's possible to load content into the DOM, but that only allows me to deal with HTML. (And potentially embedding some media types such as Images etc.) I don't see any obvious way to deal with embedding response types such as JSON and XML without having to construct special cases for how to renderer each type into HTML.

I've considered if there might be some work around involving frames or changing window.location to load the content, but I can't see any way to make it work.

Is it at all possible to do what I'm looking for, or can you suggest any elegant workarounds that might help?

Edit:

For a bit more background - This is for some work on an API browser. I've no problem doing what I need with GET and POST - it's PUT and DELETE that are awkward, since I can't support them directly with HTML. At the moment the implementation uses some server-side trickery and a hidden _method field on the form, that allows POST requests to be overloaded into PUT/DELETE/OPTIONS/whatever, but ideally I'd like to take that logic out of the server side, and do the equivalent using javascript.

Right now I don't think it's actually do-able, but I'm hoping that someone can prove me wrong, or find an elegant work-around.

like image 581
Tom Christie Avatar asked Nov 27 '25 15:11

Tom Christie


1 Answers

I wonder if you can open a new window or create an iframe where the URL you pass to the window or iframe is not an absolute URL for the resource on the web, but a data uri. You'd need to sniff out the mime-type of the response and then encode the body of the response.

No idea if it'd work, but I'd be interested to hear if you do manage to achieve it.

Other things to explore: the BlobBuilder (an HTML5 feature) and creating a "sourceless" iframe (where the src is just about:blank) with a custom mime type and then use document.write to write into the iframe document (some of the code in AppleOfMyIframe could be of use).

like image 142
Prem Avatar answered Nov 29 '25 04:11

Prem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!