我在我的Rails应用程序中添加了一个AJAX脚本,以便我的表单会自动将汽车对象添加到汽车供稿中。在幕后,汽车就像应该的那样张贴到饲料上。然而,在我刷新然后新车出现之前,网页上没有任何反应。如何在没有页面刷新的情况下实现这一目标?
AJAX脚本 的 create.js.rb
$('#car_feed').replace("<%= escape_javascript(render 'shared/feed') %>");
$('#new_car').replace("<%= escape_javascript(render 'shared/car_form') %>");
$('#car_errors').html("<%= escape_javascript(render 'shared/error_messages', object: @car) %>");
以下表格:
_car_form.html.erb
<%= form_for(@car, html: {multipart: true, remote: true}) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<h3> Add Your Car</h3>
<div class="field">
<%= f.text_area :year, placeholder: "Year i.e. '1993" %>
<%= f.text_area :brand, placeholder: "Brand i.e. 'Ford'"%>
<%= f.text_area :model, placeholder: "Model i.e. 'Mustang'" %>
<%= f.text_area :vin, placeholder: "17 digit VIN number" %>
<%= f.text_area :mileage, placeholder: "Current Car Mileage" %>
</div>
<p> Add a Photo </p>
<span class="picture">
<%= f.file_field :picture, accept: 'image/jpeg,image/gif,image/png' %>
</span>
<%= f.submit "Add Car", class: "btn btn-add btn-primary" %>
<% end %>
<button class="btn btn-hide btn-primary"> Hide Form </button>
<script type="text/javascript">
$('#car_picture').bind('change', function() {
size_in_megabytes = this.files[0].size/1024/1024;
if (size_in_megabytes > 5) {
alert('Maximum file size is 5MB. Please choose a smaller file.');
}
});
</script>
以及应通过AJAX添加的Feed:
_feed.html.erb
<div id="car_feed">
<% if @feed_items.any? %>
<ul class="cars">
<%= render @feed_items %>
</ul>
<% else %>
<h3> You haven't added any cars yet.</h3>
<h3> Add one in the sidebar!</h3>
<% end %>
</div>
rails log中的一切看起来都很好:
Started POST "/login" for 128.252.110.217 at 2015-02-27 01:16:38 +0000
Processing by SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"gFDS0iSBZl38m/LMPXulLCxvNgsjMQWMA3P/K+VEVzzTvQfTShKud3UaCRRlz6jL4JFtnwFiA6jukBfxZ7WpIw==", "session"=>{"email"=>"andrew@example.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."email" = ? LIMIT 1 [["email", "andrew@example.com"]]
(0.2ms) begin transaction
(0.1ms) commit transaction
Redirected to http://rails-tutorial-ajhausdorf.c9.io/
Completed 302 Found in 129ms (ActiveRecord: 1.2ms)
答案 0 :(得分:-1)
我认为你应该使用railscasts.com发布的关于他们的“选择”或“jquery输入”库“rayan bates”