0

尝试使用 js.erb 文件捕获控制器方法的成功/错误。资产已创建,我从 jQuery 收到警报,但我希望来自 ERB(第一个代码片段)的消息没有出现。我做错了什么?

create_asset.js.erb

<% if @asset.errors.any? %>
    var errors = $('<ul />');
    errors.append('<li><%= escape_javascript( error ) %></li>');
    jQuery('#create_asset_message').html(errors);
<% else %>
    jQuery("form#create_asset_form").before('<div id="flash_notice"><%= escape_javascript(flash.delete(:notice)) %></div>');
    jQuery('form#create_asset_form')[0].reset();
<% end %>

create_asset 控制器方法

  def create_asset
    @asset = Asset.new(:name                  => params[:name],
                       :description           => params[:description],
                       :serial_number         => params[:serial_number],
                       :asset_manufacturer_id => params[:asset_manufacturer_id],
                       :asset_model_id        => params[:asset_model_id],
                       :image_filename        => params[:image_filename])

    respond_to do |format|
      format.js
    end
  end

查看[部分]:

<%= form_tag create_asset_assets_path, :method => :get, :id => "create_asset_form", :remote => true do %>
    <div class="row-fluid">
        <h3>Choose your template: </h3>
        <%= collection_select(:asset, :id, @asset_templates,:id,:name, {:prompt => "Select your template..."}, {:class=>'chzn-select', :onchange => "update_asset_form_div(this.value)"}) %>
    </div>
    <br/>
    <%= render :partial => "create_asset_form", :object => @asset_template, :manufacturers => @manufacturers %>

    <%= submit_tag "Create Asset", :disable_with => "Please wait..." %>

    <div id="create_asset_message"></div>
<% end %>

jQuery的阿贾克斯

jQuery('form#create_asset_form').submit( function () {
    alert("You got here")
    jQuery.ajax({
        url: "/assets/create_asset.js",
        type: "GET",
        data: {"name"          : jQuery('#name').val(),
            "description"   : jQuery('#description').val(),
            "serial_number" : jQuery('#serial_number').val(),
            "asset_manufacturer_id" : jQuery('#manufacturer_select').val(),
            "asset_model_id"        : jQuery('#models_select').val(),
            "image_name"    : jQuery('#image_name').val()},
        dataType: "html"
    });
    return false;
});
4

1 回答 1

1

将数据类型设置为脚本确实很有帮助...

我的 ajax 查询应该是这样的(使用datatype: "script"而不是"html"):

jQuery('form#create_asset_form').submit( function () {
    alert("You got here")
    jQuery.ajax({
        url: "/assets/create_asset.js",
        type: "GET",
        data: {"name"          : jQuery('#name').val(),
            "description"   : jQuery('#description').val(),
            "serial_number" : jQuery('#serial_number').val(),
            "asset_manufacturer_id" : jQuery('#manufacturer_select').val(),
            "asset_model_id"        : jQuery('#models_select').val(),
            "image_name"    : jQuery('#image_name').val()},
        dataType: "script"
    });
    return false;
});
于 2012-07-02T20:41:41.857 回答