naokazuterada
1/24/2013 - 2:23 PM

call.js

match 'get_page' => 'general#get_page', :via => 'get'
require 'net/http'
require 'uri'
 
class GeneralController < ApplicationController
 
  def index
  end
 
  # For ajax error like "Origin http://localhost is not allowed by Access-Control-Allow-Origin."
  def get_page 
 
    url = URI.parse(params[:url])
    req = Net::HTTP::Get.new(url.path)
    res = Net::HTTP.start(url.host, url.port) {|http|
      http.request(req)
    }
 
    headers['Access-Control-Allow-Origin'] = 'http://localhost:3000/' 
    headers['Access-Control-Request-Method'] = '*' 
    render :text => res.bod
    
  end

end
$(function(){
    // #url is textfield
    $("#url").change(function(){
        var url = '/get_page?url='+$(this).val();
        $.ajax({
            url: url,
            cache: false,
            dataType: 'html',
            success: function(html){
                var title = html.match("<title>(.*?)</title>")[1];
                console.log(title);
            }
        });
    });
});