简体   繁体   中英

How do I display an external site in my rails view?

I'm trying to build a view in my Rails app that mirrors a page on an external site. So basically, instead of linking to the external page, that external page will be shown in my view already.

Is there a way to do this without using iFrame or is that the only way?

You can use Javascript to load the content from an external site, and show it in your view.

Here is the code:

<script>
    $("#externalSiteContent").load("http://www.example.com/index.html");
</script>
<div id="externalSiteContent"></div>

This is an all-rails approach:

class YahooController < ApplicationController

  layout false

  def show 
    url = URI.parse('http://www.yahoo.com/')
    req = Net::HTTP::Get.new(url.to_s)
    res = Net::HTTP.start(url.host, url.port) {|http|
      http.request(req)
    }

    @body = res.body
  end

end

In the view

# views/yahoo/show.html.haml
= @body.html_safe

Of course, you'll need a route to this.

# routes.rb
get '/yahoo', :to => 'yahoo#show' 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM