Embed HTML from external server
Problem: We want to populate part of our page with HTML located on another server.
.
Easy Solution
Use <iframe>. Just add the tag and you're done.
Complex Solution
Use JSONP. This will enable you to tightly integrate the external partial into your page.
Set up you server to handle JSONP requests. E.g. in Rails it's as easy as changing
render 'home', layout: nil
to
render json: {:html => render_to_string('home', layout: nil)}, callback: params[:callback]
The server will now respond to
home.html?callback=CALLBACK
request with:
CALLBACK( {"html": "<div id="home">Hello From Home!</div>"} )
Initiate a JSONP request. With jQuery it will look like this:
$.getJSON(url+'?callback=?', function(data) { document.getElementById(id).innerHTML = data.html; });
That's it. jQuery automatically generates a unique URL for the
callback
function and automatically executes it after retrieval, calling thefunction(data)
method.