简体   繁体   中英

Rails: Respond with js to Ajax request

I encountered some weird behaviour when using an ajax request to get a response from a rails controller action.

$.ajax({
    type: 'GET',
    url: '/notifications',
    success: function(result) {
        eval(result);
    }
});
def index
    respond_to do |format|
        format.html { redirect_to root_url, alert: 'Page not accessible' }
        format.js
    end
end

So this respond_to block works fine when using requests with rails' remote: true option, but with the ajax call it just redirects the request to root_url .

When specifying json as dataType of the Ajax request. The so returns the JavaScript just fine, but because it is not valid json , eval() does not run it.

Is there a way too either start a rails remote request from within JavaScript or specify a data type with which the returned JavaScript is executable?


Even specifying dataType: 'text/javascript', in the ajax call does not do the trick.

So this respond_to block works fine when using requests with rails' remote: true option, but with the ajax call it just redirects the request to root_url

So the request format that is coming to the controller is HTML not JS . Using dataType: 'script' generates the request as JS and should fix your problem.

$.ajax({
  type: 'GET',
  dataType: 'script',
  url: '/notifications'
});

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