简体   繁体   中英

Calling a js.erb file with ajax in ruby on rails

I have the following jQuery function that I'm trying to use with rails to create an alert on a page.

    $("#buttonID").click(function() {
      foo = $("#otherID").val();
      $.ajax({
        submitVar: foo //no idea what to do here
        type: 'GET',
        url: 'controller/action_js',
        dataType: 'script'
      });
    });

in my controller

    def action_js
      @item = Item.find(:name => foo)
      respond_to do |format|
        format.js
      end
    end

action_js.js.erb:

    alert(@item);

I'm trying to make it so that when I click the button with id = 'buttonID', an alert appears showing the item in the database whose name equals the value of the field with id = 'otherID'. I have no idea how to use js.erb properly with ajax or how to pass a variable to my js.erb file. Clicking the button currently does nothing.

You can use

jQuery.getScript() method to run it. See details, http://api.jquery.com/jQuery.getScript/

or

$.ajax({
    ..., 
    dataType: "script",
    ..
})

Both these above methods will fetch a script and then execute it.

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