Rails3 UJS更新未显示

Rails3 UJS update not displaying

本文关键字:显示 更新 UJS Rails3      更新时间:2023-09-26

我在获取更新页面显示的UJS调用时遇到问题。我想在选择框发生变化时更新div的值(我已经在谷歌上搜索了很多地方,但都没有用)。

我这样设置更改功能(我使用的是Haml):

%script
  $("#timesheet_worker_id").change(function() {
  -# This works, so we know we're responding to the change event: 
  -# alert('Fired the change function');
  $.ajax({url: "/timesheet_show_worker_name",
  async: false,
  data: 'selected=' + this.value,
  dataType: 'script'})
  });
  });

我的控制器有以下内容:

def show_worker_name
  calculated = 'Adam Bilbo'
  render(:update) {|page|
    ### The following works just fine!
    #page << "alert('This is a test')"
    ### This doesn't; DOM is updated but not displayed; test data for now
    page << "$('#timesheet_worker_name').val('Adam Bilbo')"
  }
end

我的视图有(我使用simple_form):

=f.association :worker, :collection => Worker.all(:order => 'worker_number'), :prompt => 'Select a worker', :label_method => :worker_number, :label => "Worker Number", :input_html => {:class => 'startField'}
%p{:id => :timesheet_worker_name}

当ajax调用完成时,我检查DOM,值就在那里;即,在控制台:

$('#timesheet_worker_id").val()

显示"Adam Bilbo",但该值未显示在我的页面上。

我正在运行Rails 3.0.9和gem-jquery Rails 1.0.9;如果能帮我弄清楚我忽略了什么,我将不胜感激!谢谢

已解决-@iWasRobed的解决方案如下。然而,基本问题是在更新"#timesheet_worker_name"时使用val()而不是text(),所以我最初的方法也适用于这种更改。

让我们稍微重组一下。。。

:javascript
  $('#timesheet_worker_id').change(function() {
    $.ajax({
      url: '/timesheet_show_worker_name',
      data: { 'selected': $(this).value },
      success: function (json) { 
        $('#timesheet_worker_name').text(json.name);
      },
      error: function (response) {
        alert('Oops, we had an error.');
      }
    });
  });

您的控制器操作将是:

def show_worker_name
  calculated = 'Adam Bilbo'
  render :json => { :name => calculated }, :status => :ok
end