简体   繁体   中英

auto ajax call in ruby on rails is not working

I'm trying to do this: after my homepage loads (home.html.erb), call ajax to update the value of a tag on the same page. Here is what I have in my home.html.erb

<script>
  $(document).ready(function() {
    $.ajax({
      type: 'GET',
      url: '<%= url_for(action: "home") %>'
    });
  });
</script>

and my home.js.erb

var id = 5;
$('#jquerylogo').html(id);

and my controller

def home
  respond_to do |format|
    format.html # home.html.erb
    format.js
  end
end

but ajax is not called and the code doesn't work. why? thanks.

Sometimes ujs issues are tricksie.

I would start by adding a dataType to the ajax call to force the controller to respect it's type.

$(document).ready(function() {
  $.ajax({
    type: 'GET',
    dataType: 'script',
    url: '<%= url_for(action: "home") %>'
  });
});

Things to look for are:

  • Check the javascript console to see what (if any) errors you have
  • Check your log to see if the request is made/received/rendered as html

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