Saturday, March 27, 2010

JSON-P on Rails with jQuery

How to do render JSON-P data format on Rails, it's not complicated.. here the codes

firstly, you must render json format from your controller

def request
respond_to do |format|
format.json do
render :json => {:say => "Hello"}.to_json, :callback => params[:callback]
end
end
end

Next, you can access the json format data with ajax, exactly with jQuery

jQuery.ajax({
url:"http://127.0.0.1:3000/example/request.json?callback=?",
type:"jsonp",
method:"GET",
success:function(data)
{
console.log(data);
}
});

With jQuery ajax request make you can access the site with across domain, so you can access it from other domain.

No comments:

Post a Comment