0

在我正在处理的 Rails 应用程序中,我想刷新/重新加载控制器的索引方法而不刷新视图。例如,假设我有这个作为我的索引:

def index
    @title =params[:title]   
end 

和 html.erb:

<script>
function changeField() {
  var newTitle = "Alerts"
  $.ajax({
    url: 'index?title=' + newTitle,
    type: 'POST',
    contentType: 'application/json',
    data: '',
    dataType: 'script',
    headers: {
      'X-CSRF-Token': '<%= form_authenticity_token.to_s %>'
    },
  complete: function () {
    alert('<%=@title%>');
  }
  });
}
</script> 

<button type="button" onclick="changeField()"></button>

我遇到的问题是它不会在视图上重新加载@title 变量,所以我得到的是原始标题而不是新标题。

4

1 回答 1

1

When page was loading alert('<%=@title%>') equals alert('first value') and after set a new value javascript code can't be reloaded. If you look html code you can see first value but not second

I think you can add this code to you controller

respond_to do |format|
  format.html # index.html.erb
  format.js { render :json { :title => params['title'] || @title }.to_json }
end

and add to js code success: function(data) { alert(data['title']) }

于 2013-07-24T20:21:31.823 回答