Ruby on Rails - 使javascript函数与ajax一起工作

时间:2022-08-25 18:43:27

I have been trying to figure something out for a while and am not sure the best way to go about my current problem. First I will let you know what I am trying to do. A user enters text into a text box and then are brought to the next page where their input is split up into words and each word is turned into a link (the link will be a search but that does not matter at the moment). The thing is that I want this to work with ajax. Now I have the page with the textbox successfully using ajax to go to the "show" page, but I cannot find the best practice online for getting my javascript that splits up the words to be executed alongside the ajax render call for "show". Here is my current code.

我一直在尝试解决一些问题并且不确定解决当前问题的最佳方法。首先,我会告诉你我想做什么。用户将文本输入到文本框中,然后进入下一页,其中输入被分成单词,每个单词变成一个链接(链接将是一个搜索,但此刻无关紧要)。问题是我希望这与ajax一起使用。现在我使用ajax成功地使用文本框进入“显示”页面,但我无法在线找到最佳实践,以便将我的javascript拆分为与“show”的ajax渲染调用一起执行的单词。这是我目前的代码。

The create form:

创建形式:

<%= form_for @icelandic_reader, :remote => true, :html => { :class => 'form-     horizontal' } do |f| %>
   <div class="control-group">
     <div class="controls">
       <%= f.text_area :text, :class => 'text_area' %>
     </div>
   </div>

   <div class="form-actions">
     <%= button_to 'Submit', icelandic_readers_path(@icelandic_reader.id), :class => 'btn btn-primary' %>
     <%= link_to t('.cancel', :default => t("helpers.links.cancel")),
            icelandic_readers_path, :class => 'btn' %>
   </div>
<% end %>

create in the controller:

在控制器中创建:

def create
  @icelandic_reader = IcelandicReader.new(params[:icelandic_reader])

  respond_to do |format|
    if @icelandic_reader.save
      format.html { redirect_to @icelandic_reader, notice: 'Icelandic reader was successfully created.' }
      format.js
      format.json { render json: @icelandic_reader, status: :created, location: @icelandic_reader }
  else
    format.html { render action: "new" }
    format.json { render json: @icelandic_reader.errors, status: :unprocessable_entity }
  end
 end
end

create.js.erb:

 $('.icelandic_reader').html ("<%=j render :partial => 'show' %>");

in the show partial:

在节目部分:

<div id="icelandic_reader_text">

</div>

Show in the controller:

在控制器中显示:

def show
  @icelandic_reader = IcelandicReader.find(params[:id])
  gon.icelandicText = @icelandic_reader.text

  respond_to do |format|
    format.html # show.html.erb
    format.json { render json: @icelandic_reader }
  end
end

and finally the javascript function I want to fill in the "icelandic_reader_text" div, which I currently have in icelandic_readers.js.erb:

最后我要填写“icelandic_reader_text”div的javascript函数,我目前在icelandic_readers.js.erb中有这个:

window.onload = pageChecker;
function pageChecker() {
    var testElement = document.getElementById('icelandic_reader_text');

    if ( !testElement ){
        setTimeout(pageChecker, 50);
    }
    else {
        var myText = gon.icelandicText;
        console.log("test1");
        var words = myText.split(/[\s]+/);
        console.log("test2");
        var numWords = words.length;
        var textToInsert;

        for (var i = 0; i < numWords; i++) {
            console.log("inside for loop");
            textToInsert += "<a href=#>" + words[i] + "</a>" + " ";
        }

    document.getElementById('icelandic_reader_text').innerHTML = textToInsert;
    }

}

The first part of the function before else I got from an answer here in stack overflow on how to get ajax to work with it, but it didn't work. I am starting to think I have to implement in a different way than using window.onload. I am kind of new to Ruby so I would just like to know if there is a different way of thinking I should be using for this problem. Also I am using rails 3.2.6. Thanks to anyone who answers!

函数的第一部分之前我从堆栈溢出中得到答案如何让ajax与它一起工作,但它没有用。我开始认为我必须以与使用window.onload不同的方式实现。我是Ruby的新手,所以我想知道是否有一种不同的思维方式我应该用于解决这个问题。我也使用rails 3.2.6。感谢任何回答的人!

2 个解决方案

#1


0  

You can attach an event listener to the form like this (using jQuery):

您可以像这样(使用jQuery)将事件监听器附加到表单:

$(document).ready(function() {
  $("#icelandic_reader_form").bind('ajax:success', function(data, status, xhr) {
      // code to execute after form successfully submitted
  });
}

I think the form id in my example is wrong, use the one given by rails.

我认为我的示例中的表单id是错误的,使用rails给出的那个。

#2


0  

Its possible be that window.onload is not triggering at all, or that its triggering before the show gets rendered, and therefore can't find the element #icelandic_reader_text

可能是window.onload根本没有触发,或者它在show渲染之前触发,因此无法找到元素#icelandic_reader_text

  1. if you can, define pageChecker() in some file that you load in the layout so its ready to fire.
  2. 如果可以,请在布局中加载的某个文件中定义pageChecker(),以便随时触发。

  3. try this in create.js.erb:

    在create.js.erb中尝试这个:

    $('.icelandic_reader').html("<%=j render :partial => 'show' %>").each(pageChecker);
    //By chaining the actions with jquery, things should happen in the correct order.
    

You could also rewrite pageChecker(), where $(this) references $('.icelandic_reader')

你也可以重写pageChecker(),其中$(this)引用$('。icelandic_reader')

    function pageChecker() {

        var myText = gon.icelandicText;
        console.log("test1");
        var words = myText.split(/[\s]+/);
        console.log("test2");
        var numWords = words.length;
        var textToInsert;

        for (var i = 0; i < numWords; i++) {
            console.log("inside for loop");
            textToInsert += "<a href=#>" + words[i] + "</a>" + " ";
        }

        $(this).find('#icelandic_reader_text').append(textToInsert)
    }

#1


0  

You can attach an event listener to the form like this (using jQuery):

您可以像这样(使用jQuery)将事件监听器附加到表单:

$(document).ready(function() {
  $("#icelandic_reader_form").bind('ajax:success', function(data, status, xhr) {
      // code to execute after form successfully submitted
  });
}

I think the form id in my example is wrong, use the one given by rails.

我认为我的示例中的表单id是错误的,使用rails给出的那个。

#2


0  

Its possible be that window.onload is not triggering at all, or that its triggering before the show gets rendered, and therefore can't find the element #icelandic_reader_text

可能是window.onload根本没有触发,或者它在show渲染之前触发,因此无法找到元素#icelandic_reader_text

  1. if you can, define pageChecker() in some file that you load in the layout so its ready to fire.
  2. 如果可以,请在布局中加载的某个文件中定义pageChecker(),以便随时触发。

  3. try this in create.js.erb:

    在create.js.erb中尝试这个:

    $('.icelandic_reader').html("<%=j render :partial => 'show' %>").each(pageChecker);
    //By chaining the actions with jquery, things should happen in the correct order.
    

You could also rewrite pageChecker(), where $(this) references $('.icelandic_reader')

你也可以重写pageChecker(),其中$(this)引用$('。icelandic_reader')

    function pageChecker() {

        var myText = gon.icelandicText;
        console.log("test1");
        var words = myText.split(/[\s]+/);
        console.log("test2");
        var numWords = words.length;
        var textToInsert;

        for (var i = 0; i < numWords; i++) {
            console.log("inside for loop");
            textToInsert += "<a href=#>" + words[i] + "</a>" + " ";
        }

        $(this).find('#icelandic_reader_text').append(textToInsert)
    }