开发者

How to display a certain number of array items in rails

I have an array and I want to display only 4 items at a time and when I click on Next it will display the 4 next items. View Code :

<table>
<tr>
  <th></th>
  <th>3</th>
  <th>2</th>
  <th>1</th>
  <th>1</th>
  <th>2</th>
  <th>3</th>
  <th></th>

</tr>
<% count = 0 %> 
<% while count < 4%>
  <tr class="match_row" value="<%=count%>">
    <th id="left_competitor"><%= @matches[count][0].title %></th>
    <% (1..6).each do |i|%>
      <th>  <input type="radio" class="group_<%=count%>" name="<%=count%>" value="<%= i%>"><br></th>
    <% end %>
    <th id="right_competitor"> <%= @matches[count][1].title %></th>
  </tr>
  <br />
  <% count += 1 %>
<% end %>
<br />
</table>
<input id="save_votes" type="button" value="Next">

Now here is the CoffeeScript code :

move_to_next_match = ->
  $("#save_votes").click -> display_next_competitors()

display_next_competitors = ->
  project_id = document.getElementById("project_id").value
  match_rows = $('.match_row')
  results = []
  for i in [0...match_rows.length]
    do (i) ->
      radios = $(".group_#{i}")
      for j in [0...radios.length]
        do (j) ->
          if radios[j].checked
            count = radios[j].g开发者_开发百科etAttribute 'name'
            number = radios[j].getAttribute 'value'
            results.push("#{count} #{number}")
  data = "{\"get_matches_results\": \"#{results}-#{project_id}-#{marker}\"}"
  $.ajax({
  type: "POST"
  url: "projectss/pca_results"
  data: "data=" + data
  })
  location.reload(true);

My idea is to let the variable count in view (<%count = 0%>) take the value of a variable instead of 0 but I can't figure out how to do this. Any ideas ?


This looks like a lot of logic in your view templates, reminds me more of PHP.

Maybe you can table a look at this: http://railscasts.com/episodes/174-pagination-with-ajax

Ryan uses a Gem to handle the pagination (Lookup Kaminari or WillPaginate) and then uses unobstructive jQuery to handle the AJAX component.


It's not entirely clear from your question what problem you're experiencing, but I'm guessing that it has to do with the code

$.ajax({
type: "POST"
url: "projectss/pca_results"
data: "data=" + data
})
location.reload(true);

which sends a request to the server that potentially changes the page's content, then immediately refreshes the page without waiting for a response. There's a race condition there: Sometimes the page will refresh before its content is updated, sometimes after. You should instead write

$.ajax({
type: "POST"
url: "projectss/pca_results"
data: "data=" + data
success: -> location.reload(true);
})

to ensure that the page is refreshed only after the update is processed. Or, better yet, write a success callback that updates the HTML on the page then and there, rather than refreshing the entire page. Your users will thank you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜