Rails Ajax: .js.erb rendered as text, not JS

前端 未结 4 1050
情话喂你
情话喂你 2020-12-09 23:05

I\'m having a trouble with rails3 to render Javascript (If this is relevant, I use JQuery and it works fine since it\'s used in numerous other parts of the application) inst

相关标签:
4条回答
  • 2020-12-09 23:10

    Seems a little late to be providing this answer, but better late that never.

    You are mixing up respond_to and respond_with. At the top of your controller class use respond_to :js, :html. Then put this in your edit action

    def edit
      @user_repreneur = UserRepreneur.find_by_id_view(params[:id])
      respond_with @user _repreneur
    end 
    
    0 讨论(0)
  • 2020-12-09 23:18

    If you are on rails,

    Simple fix: Add data-type="script" to the form. Source: https://github.com/rails/jquery-ujs/wiki/Unobtrusive-scripting-support-for-jQuery

    0 讨论(0)
  • 2020-12-09 23:25

    js.erb files render as text if you don't have the jquery_ujs lib included in your application.js file:

    //= require jquery
    //= require jquery_ujs
    

    And you'll need the following gems in your gemfile:

    gem 'jquery-rails'
    gem 'jquery-ui-rails'
    
    0 讨论(0)
  • 2020-12-09 23:34

    I don't think the problem is with your server-side code. It all looks good to me. And the fact that it is rendering edit.js.erb proves that your server-side code is working fine.

    The problem is on your client-side. When it receives the Ajax response, it isn't executing it as javascript. It is executing it as text.

    I have recently had this problem myself and I wish I had my code with me but I'm at work. However, I personally wrote the jQuery Ajax request instead of relying on :remote => true since that option is mostly used in forms.

    Try giving your link_to an id and then put this jQuery in your application.js or wherever.

    $('#link_id').click(function(){
       $.ajax({
          type : 'GET',
          url : '/:controller/:action/',
          dataType : 'script'
       });
       return false;
    });
    

    This will grab the link's click event, send a request to the server which should return your edit.js.erb file, and then execute it as script.

    Mind you, there is a lot of security concerns to take into account as well as authenticity tokens and the like. However, this should get your alert to execute and get you on the right path to completing your app.

    Read up on jQuery's Ajax for further options and details about POSTing data as well.

    Hope this helps.

    UPDATE: Other possible solutions include using UJS as a Javascript driver. You can read the documentation at https://github.com/rails/jquery-ujs and view a Railscast on the topic Unobtrusive Javascript using UJS.

    0 讨论(0)
提交回复
热议问题