jzcada
Last Updated: February 25, 2016
·
426
· petrbela
D1d8b6e6a25f6fa7bc5f89bc33aa3422

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.

  1. 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]

  2. The server will now respond to home.html?callback=CALLBACK request with:
    CALLBACK( {"html": "<div id="home">Hello From Home!</div>"} )

  3. Initiate a JSONP request. With jQuery it will look like this:
    $.getJSON(url+'?callback=?', function(data) { document.getElementById(id).innerHTML = data.html; });

  4. That's it. jQuery automatically generates a unique URL for the callback function and automatically executes it after retrieval, calling the function(data) method.

Say Thanks
Respond