Cross Domain AJAX Request And Rails

Because The Browser have the Same-origin policy

Same-origin policy it’s say:

A web browser permits scripts contained in a first web page to access data in a second web pageand only if both web pages have the same origin.

And it’s purpose is:

Prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page’s Document Object Model.

So if We want to use a web ajax to get the data from the cross domain resource How can We do it?



$.ajax({ type: 'GET',  
    url: "http://localhost:3000/v1/questions/1/options", 
    dataType: 'jsonp', 
    success: get_options_data_success, 
    error: null 

var get_options_data_success = 
function(data) { something you want }


render json: Question.all, :callback => params[:callback]

If use above, ajax will add ?callback=(Random function name)

such as: ?callback=jQuery21306889237540308386_1436178704662

and the Rails will get the callback params and will resoponse a porcess data /**/
jQuery213014021378150209785_1436178755583( …origin josn data rails will response…)

such as: /**/jQuery213014021378150209785_1436178755583( [{"question_id":1,"id":5,"description":"50+","votes_count":1}])

so Ajax can get the data Rails response and cross domain


Browser does not allow cross domain AJAX requests due to security issues.
Cross-domain requests are allowed only if the server specifies same origin security policy.
Read more about Cross-origin resource sharing (CORS)

If you want to enable CORS in Rails , you can add below code to ApplicationController

class ApplicationController < ActionController::Base 
  protect_from_forgery unless: -> { request.format.json? } 
  after_filter :set_cross_domain_access

  def set_cross_domain_access 
    headers['Access-Control-Allow-Origin'] = '*' 
    headers['Access-Control-Allow-Methods'] = 'POST, GET' 
    headers['Access-Control-Allow-Headers'] = '*' 


Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see