2

ROR での Ajax に関する記事をいくつか読んだ後でも、Ajax の使用方法についてまだ混乱しています。

私のプロジェクトにはmain/index.htmlandがあります。main_controller以下の機能を実現したい。

のリンクをindex.htmlクリックすると、RSS コンテンツがインデックスに表示されます。別のWebページにジャンプすることで機能を果たしました。しかし、Ajaxの使い方がわかりません...

索引

 <h1>Listing Jobs</h1>
<table>
    <tr>
        <th>Source</th>
        <th></th>
    </tr>
<% @jobs.each do |job| %>
    <tr>
        <td><%= job.source %></td>
        <td>
            <%= link_to 'Show', #:controller=>'main', :action=>'show',
                :id=>job.id,:remote=>true, "data-type"=>:json, :class=>'updateJob'%>
        </td>
    </tr>
<% end %>
</table> 

<script type="text/javascript" charset="utf-8">

$(function(){
#   $('#'+job.id).bind("click",function(){
#       $('#showJob').append('Hi')
#   })

$('#'+job.id).bind("ajax:success",function(data, status, xhr){
    ("<h1>hello</h1>").appendTo("#showJob") 
})

})
</script>

show.html

<div id="showJob">
    </div>
<table>
    <tr>
        <th>Source</th>
        <th>Link</th>
    </tr>
<% @feed.items.each do |item| %>
    <tr>
        <th><%= item.title %></th>
        <th><%= item.link  %></th>
    </tr>
<% end %>

</table> 

メインコントローラー

require 'rss'
require 'rss/1.0'
require 'rss/2.0'
require 'open-uri'

class MainController < ApplicationController
    #get /jobs
    def index
        @jobs=Job.all

        respond_to do |format|
            format.html # index.html.erb
            format.json {render:json=>@jobs}
        end
    end

    def welcome
        @num_sources =Job.count
    end

    def show
        job=Job.find(params[:id])
        url=job.url
        open(url) do |rss|
            @feed = RSS::Parser.parse(rss)
        end

        respond_to do |format|
        # format.html do
        #   render :partial=>'main/show'
        # end
        format.json {render :json=>@feed}
        end
    end

end
4

1 に答える 1

0

イベントにバインドする代わりに、click処理する ajax イベントのバインドを追加します。通常、これには次のajax:successイベントが含まれます。

$(function(){
    $('#'+job.id).on("ajax:success", function(data, status, xhr){
        // do something with 'data' json object
    });
});

イベントの完全なリストはこちらでご覧いただけます

レンダリング時にコントローラーで「json」形式を使用するには、リンクを次のように変更します。

<%= link_to 'Show', { :controller=>'main', :action=>'show', :id=>job.id }, 
                    :data => {:remote=>true, :type=>:json}, :class=>'updateJob'%>

URL を構成するハッシュ (コントローラー、アクション、ID) を適切に機能させるには、他の属性とは別のハッシュで渡す必要があることに注意してください。routes.rbジョブをファイル内のリソースとして設定している場合は、これをさらに簡単にすることができます。

<%= link_to 'Show', job, :data => {:remote=>true, :type=>:json}, :class=>'updateJob'%>
于 2013-03-03T03:24:52.530 に答える