简体   繁体   English

Ruby在Rails应用程序上加载页面时出现JavaScript问题

[英]javascript issue on page load with ruby on rails application

background: I am creating a wiki clone with users that can create wikis. 背景:我正在与可以创建Wiki的用户一起创建Wiki克隆。 The users can also add collaborators which are fellow users to contribute to the wikis. 用户还可以添加协作者,这些协作者是对Wiki做出贡献的同行用户。

I am having trouble with the the javascript when I get to that page by clicking a link. 通过单击链接进入该页面时,我在使用javascript时遇到了麻烦。 When I re-load this same page the javascript works. 当我重新加载同一页面时,javascript正常工作。 Most of the javascript is for an autocomplete search function that renders names of users at the bottom of the page that matches the letters being typed into the search box. 大部分javascript用于自动完成搜索功能,该功能可在页面底部呈现与在搜索框中键入的字母匹配的用户名。

Within my functionality I have a link on the show#wikis view that links to the edit#wikis view which looks like this: 在我的功能范围内,我在show#wikis视图上有一个链接,该链接指向如下所示的edit#wikis视图:

 #views/wikis/show.html.erb
 <%= link_to "Edit", edit_wiki_path(@wiki), class: "btn btn-success" %>

Once the link is clicked and the edit#wikis page appears the page loads but the javascript and ajax calls do not work. 单击链接并显示edit#wikis页面后,页面将加载,但javascript和ajax调用不起作用。 The views/wikis/edit.html.erb page is below, however the important part of the code where most of the ajax is being used is the form partial for collaborators at the bottom: 下面是views/wikis/edit.html.erb页面,但是使用大多数ajax的代码的重要部分是底部的协作者部分表单:

    <h1>Edit Wiki</h1>

 <div class="row">
   <div class="col-md-4">
     <p>Guidelines for Wikis</p>
     <ul>
       <li>Make sure the it rhymes.</li>
       <li>Don't use the letter "A".</li>
       <li>The incessant use of hashtags will get you banned.</li>
     </ul>
   </div>
   <div class="col-md-8">
     <%= form_for @wiki do |f| %>
       <div class="form-group">
         <%= f.label :title %>
         <%= f.text_field :title, class: 'form-control', placeholder: "Enter post title" %>
       </div>
       <div class="form-group">
         <%= f.label :body %>
         <%= f.text_area :body, rows: 20, class: 'form-control', placeholder: "Enter post body" %>
       </div>
       <%if policy(@wiki).edit_form_settings? %>
         <div class="form-group">
          <%= f.label :public, class: 'checkbox' do %>
            <%= f.check_box :public %> Public wiki
          <% end %>
        </div>
      <% end %>
       <div class="form-group">
         <%= f.submit "Save", class: 'btn btn-success' %>
       </div>
     <% end %>
   </div>
 </div>
<%if policy(@wiki).edit_form_settings? %>
 <%= render partial: "collaborations/new", locals: { wiki: @wiki, collaboration: @collaboration} %>
<% end %>

The form partial from views/collaborations/_new.html.erb is listed below: 下面列出了views/collaborations/_new.html.erb部分表格:

<%= form_for [wiki, collaboration] do |f|%>

<div class = "col-md-8">

    <div class = "form-group">
      <%= f.label :user_name %>
      <%= f.text_field :user_name, class: 'form-control', placeholder: "Enter name"  %>
    </div>
    <%= f.hidden_field :user_id %>
    <div class = "form-group">
      <%= f.submit class: 'btn btn-success' %>
    </div>
  </div>

    <div id="user_data" class="dropdown">
  <ul class="list-group" style= "width:50%">
    <!-- <li class="list-group-item">Cras justo odio</li>
    <li class="list-group-item">Dapibus ac facilisis in</li>
    <li class="list-group-item">Morbi leo risus</li>
    <li class="list-group-item">Porta ac consectetur ac</li>
    <li class="list-group-item">Vestibulum at eros</li> -->
  </ul>
</div>

</div>

  </div>

</div>
<%end%>

I have the javascript in the assets/javascripts/collaborations.js.erb file: 我在assets/javascripts/collaborations.js.erb文件中包含了javascript:

$(document).ready(function()
{


     $('#collaboration_user_name').on('keyup', function() { 

      text = $(this).val();
      // alert(text);

      $.ajax({ url: "/collaborations?collaboration="+text, 
        beforeSend: function( xhr ) { 
          xhr.overrideMimeType( "text/plain; charset=x-user-defined" ); 
        } 
      }).done(function( data ) {
        console.log( "data:", data ); 
        users = JSON.parse(data);

        $("#user_data ul li").remove();
        $.each( users, function( index, value ) {
          $("#user_data ul").append("<li class='list-group-item' value ="+ users[index].id+">"+users[index].name+ ", " +users[index].email+ "</li>"); 
        });
      <% @user = "data" %>;
        $("#user_data").append(JSON.parse(data).name);
        $(' .list-group-item').click(function() {
        //alert( $(this).val() );
            $('#collaboration_user_name').val($(this).text().split(",")[0]);
           $('#collaboration_user_id').val($(this).val());
      });
    });
 });


});

lastly the controller action that the ajax calls is collaboration_search in controllers/collaborations_controller.rb : 最后,所述AJAX调用控制器动作是collaboration_searchcontrollers/collaborations_controller.rb

class CollaborationsController < ApplicationController
  respond_to :html, :js
def collaboration_search
     #name_search = params[:collaboration][:user_name].to_s
     @users_by_name = User.where('name Like ?', "%#{params[:collaboration]}%").limit(4)
     puts @users_by_name.to_a
      render json: @users_by_name
  end
end

I have tried removing the turbolinks gem but that hasn't fixed the problem. 我尝试删除了turbolinks gem,但是并没有解决问题。 I would appreciate any help! 我将不胜感激任何帮助!

I'm not 100% sure why your JS isn't working the first time around. 我不确定100%为什么您的JS第一次无法使用。 There could be many culprits, of which Turbolinks is often a good first guess. 可能有很多原因,其中Turbolinks通常是一个很好的第一选择。 But I think you could get closer to discovering what's going on by trying some of the following: 但是我认为您可以通过尝试以下一些方法来进一步发现正在发生的事情:

  • Throw a console.log('in here'); 抛出一个console.log('in here'); in your JS file, right within the document ready. 在您的JS文件中,就在文档中准备就绪。 When it's loaded, that should print to the Web Inspector console. 加载后,应将其打印到Web Inspector控制台。 This will help you decipher whether the file is loading (but not running correctly) or just not loading at all. 这将帮助您判断文件是正在加载(但无法正确运行)还是根本不加载。

  • Make sure there aren't any JS errors. 确保没有任何JS错误。 These would show up in red in the Web inspector. 这些将在Web检查器中以红色显示。

  • One error or weirdness might result from the way you're combining JS and ERB. 您将JS和ERB结合使用的方式可能会导致一种错误或怪异。 A .js.erb file is generally essentially a view with combined JavaScript functionality. .js.erb文件通常实质上是具有组合JavaScript功能的视图。 You'd generally keep it in the app/views directory, and tell your controller how to handle it. 您通常将其保存在app/views目录中,并告诉您的控制器如何处理它。 In this case, this looks like more or less a regular JS file -- in which case how you include it is the question that has the greatest effect on its function. 在这种情况下,这看起来或多或少是一个普通的JS文件-在这种情况下, 如何包含它是对其功能影响最大的问题。 Are you including it in your application.js file? 您是否将其包含在application.js文件中? In the <head> tag of your layout.html.erb view? 在您的layout.html.erb视图的<head>标记中? Some other way? 其他方式?

In relation to the ERBness of this file, it's worth pointing out that you don't seem to need the ERB at all. 关于此文件的ERB,值得指出的是,您似乎根本不需要ERB。 If anything, your use of ERB is potentially messing things up. 如果有的话,您对ERB的使用可能会使事情变得混乱。 The only ERB-like line I see is this one: 我看到的唯一类似ERB的行是这一行:

<% @user = "data" %>;

That line takes the Ruby/Rails variable @user and overwrites it with the string "data". 该行采用Ruby / Rails变量@user并用字符串“ data” 覆盖它。 That's almost certainly something you don't want to do. 几乎可以肯定,这是您不想做的事情。 (I'm unsure whether it will actually affect the variable, as you use it here.) (我不确定它是否会真正影响该变量,因为您在这里使用它。)

tl;dr -- I'd rename the file .js , make sure it's included in application.js , and add a console.log to the file to make sure that it's getting loaded, so you can isolate whether it's a loading issue or a JavaScript issue. tl; dr-我将文件.js重命名,确保将它包含在application.js ,并在文件中添加console.log ,以确保它已被加载,因此您可以隔离是加载问题还是加载问题一个JavaScript问题。 Also, check for JS errors, and remove the <% @user = "data" %> line. 另外,检查JS错误,并删除<% @user = "data" %>行。 Hopefully the above will get you closer to figuring out what's going on. 希望以上内容能使您更加了解正在发生的事情。

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

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