In my rails/heroku web app, I make a call to an external API, (the json result is used in the view). Currently that call is in a controller, but I am having issues with the external source being very slow, causing the page to load slow, or even time-out. I don't think I can use regular jquery/js/ajax because the API call contains my private API key. How can I make this call asynchronously?

1) Can I make the call in the controller asynchronous, or
2) Can I hide my key when making a call from the view, or
3) Is there a better way of handling this?

Thanks.

有帮助吗?

解决方案

Consider adding another route to proxy the long request. From your view, use AJAX to load that route and add the result to the DOM when it returns. Until that time, you can display a fancy spinner gif or something like loading...

For example

routes.rb

...
get '/long_calls/show' => 'long_calls#show'
get '/long_calls/show2' => 'long_calls#show2'
...

long_calls_controller.rb

class LongCallsController < ApplicationController
  def show
    @message = "*Please Wait*"
  end

  def show2
    @message = LongCall.thing_that_takes_a_long_time
  end
end

views/long_calls/show.html.erb

<script>
  $(function) {
    $.get("show2");
  }
</script>
<div id='lazyload'>
  <%= @message %>
</div>

views/long_calls/show2.js.erb

$("#lazyload").html("<% escape_javascript @message %>");
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top