尝试使用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 ajax
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;
});
答案 0 :(得分: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;
});