简体   繁体   English

在Ruby on Rails应用程序中,页面不断通过AJAX调用重新加载

[英]Page keeps reloading with AJAX call in Ruby on Rails App

I am sure this is a simple solution but it's driving me crazy. 我确信这是一个简单的解决方案,但它使我发疯。 I have a Ruby on Rails app whereby I am making a simple AJAX call to a controller action on a jQuery button click event to submit data and initiate a modal pop-up when it successfully submits. 我有一个Ruby on Rails应用程序,通过该应用程序,我对jQuery按钮单击事件上的控制器操作进行了简单的AJAX调用,以提交数据并在成功提交时启动模式弹出窗口。 See code below. 请参见下面的代码。

<script type="text/javascript">
$('.linkclass').click(function() {
  id = $(this).attr('id');
  event.preventDefault();
  $.ajax({
  url: "/controller_name/action_name/" + id,
  type: "GET",
  success: function (data) { 
      // call my modal pop-up
      $( "#dialog" ).dialog();
  }
  });
});
</script>

The only HTML that is relevant in the view for this issue is below (the modal div and the link HTML). 视图中与此问题相关的唯一HTML如下(模态div和链接HTML)。 Again, this works fine when the Javascript is in the view: 同样,当Javascript位于视图中时,这可以很好地工作:

<%= link_to "Submit your info", "/controller_name_name/action_name/#{product.id}", :id => product.id, :class => "linkclass" %>

<div id="dialog" title="Basic dialog" style="display:none">
<p>Your data has been successfully submitted!</p>
</div>

This code works perfectly when the Javascript is in the view and the page does not reload, as I want. 当我在视图中使用Javascript并且页面无法重新加载时,此代码可以完美地工作。 However, when I place this Javascript code (minus the script tags) in a separate Javascript file, it refreshes the page when the link is clicked. 但是,当我将此Javascript代码(减去script标签)放置在单独的Javascript文件中时,单击链接时它将刷新页面。 Everything submits fine but the page reloads/refreshes and I don't want it to reload. 一切提交正常,但页面重新加载/刷新,我不希望它重新加载。 Am I forgetting to add something extra to the code when I put it in a separate file? 将代码放在单独的文件中时,是否会忘记在代码中添加其他内容? The separate js file is in the assets/javascript folder and is included in the HTML (I see it in view source) so that's not the problem. 单独的js文件位于assets / javascript文件夹中,并且包含在HTML中(我在查看源代码中看到了它),所以这不是问题。

Any advice would be appreciated. 任何意见,将不胜感激。

The DOM hasn't fully loaded at the time you bind the event handler. 绑定事件处理程序时,DOM尚未完全加载。 You will have to make sure the DOM has loaded before you bind it like so: 在绑定它之前,您必须确保DOM已加载,如下所示:

$(document).ready(function(){
    $('.linkclass').click(function() {
      id = $(this).attr('id');
      event.preventDefault();
      $.ajax({
      url: "/controller_name/action_name/" + id,
      type: "GET",
      success: function (data) { 
          // call my modal pop-up
          $( "#dialog" ).dialog();
      }
      });
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM