2016-03-04 76 views
0

對象Task包含boolean字段done。如何在Ajax更新狀態後刷新頁面?而不是true - false顯示值完整 - 不完整?Rails如何藉助Ajax更新頁面

的routes.rb:

resources :tasks do 
    member do 
     post 'done' 
    end 
    end 

控制器:

def done 
    @task = Task.find(params[:id]) 
    @task.update_attributes(:done => params[:done]) 

    respond_to do |format| 
     format.js {} 
    end 

    end 

查看:

.... 
<td><%= task.done %></td> 
<td><%= check_box_tag 'done', task.id , task.done, :class => "task-check", remote: true %></td> 
.... 

<script> 
    $(".task-check").bind('change', function(){ 
    $.ajax({ 
     url: '/tasks/'+this.value+'/done', 
     type: 'POST', 
     data: {"done": this.checked}, 
    }); 
    }); 

</script> 

更新

編輯的腳本

<script> 
    $(".task-check").bind('change', function(){ 
    $.ajax({ 
     url: '/tasks/'+this.value+'/done', 
     type: 'POST', 
     data: {"done": this.checked}, 
    }).done(function(ajax_response){ 
    location.reload(); 
    }); 
    }); 

</script> 

和控制器

def done 
    @task = Task.find(params[:id]) # make sure you have this 
    @task.update_attributes(:done => params["done"]) 

    render :json => { data: "Success", is_done: params[:done] } 
    end 

如何,而無需重啓更新網頁內容?

+0

@toddmetheny我更新了我的問題 –

+0

請參閱下面的編輯。 – toddmetheny

回答

1

控制器:

def done 
    @task = Task.find(params[:id]) # make sure you have this 
    @task.update_attributes(:done => params["done"]) 

    render :json => { data: "Success", is_done: params[:done] } 
end 

查看:

.... 
<td><%= task.done %></td> 
<td><%= check_box_tag 'done', task.id , task.done, :class => "task-check" %></td> 
.... 

<script> 
    $(".task-check").on('change', function(e){ 
    // removed remote-true. you can preventDefault if you need to but doubt page tries to refresh from a checkbox getting checked. e.preventDefault() if you need it 
    $.ajax({ 
     type: "POST", 
     url: '/tasks/done', 
     type: 'POST', 
     data: {done: $('.task-check').val()}, 
    }).done(function(ajax_response){ 
     // update whatever you want after it completes 
    }); 
    }); 

</script> 

沒有測試這一點,但我寫的這些所有的時間。讓我知道,如果它不起作用後,我會找出缺少的東西。

如果您只是想將值從'incomplete'更新爲'complete',那麼您可以簡單地定位被稱爲incomplete的元素。如果它有一個類,比如'task-status',你可以定位該元素並在函數的.done部分進行更新。例如:

$('.task-status').text('Complete') 

應該替換之前所說的不完整的東西。如果是文本輸入,則可以使用.val()代替。如果它只是文本在頁面上.text()應該工作。

+0

如果腳本'網址: '/任務/ done'','路由錯誤:沒有路由匹配[POST]「/ tasks'如果更換'網址:: '/任務/' + THIS.VALUE +'/ done'' - 如何更新而無需重新啓動頁面? –

+0

我更新了我的問題 –

+0

如何在不更新值後重新啓動頁面? –