我有带有表单的广告和消息模型。两种表单均使用 Ajax 提交(remote => true)。
消息表单提交完美。它停留在同一页面并处理响应,但广告形式则不然。 两者的形式、 Controller 和脚本代码是相同的。只是从消息更改为广告..
广告形式。
<%= form_for(@advertisement, :html => {"data-parsley-validate" => true},remote: true, format: :json) do |f| %>
....
#lot of code here
....
<%end%>
广告 Controller :
def create
@advertisement = Advertisement.new(advertisement_params.merge(service_ids: params[:service_ids]))
respond_to do |format|
if @advertisement.save
format.html { redirect_to @advertisement, notice: 'advertisement was successfully sent.' }
format.json { render json: @advertisement }
else
format.html { render action: 'new' }
format.json { render json: @advertisement.errors.full_messages, status: :unprocessable_entity }
end
end
end
脚本:
$(document).ready(function() {
return $("#new_advertisement").on("ajax:success", function(e, data, status, xhr) {
alert("ok");
}).on("ajax:error", function(e, xhr, status, error) {
alert("Error registration");
});
});
提交后,我将被重定向到此链接:
http://localhost:3000/lv/advertisements.json
浏览器显示所有已发送的参数:
{"id":45,"name":"dsad","subname":"dasd","country_id":1,"region_id":3,"age":18,"height":144,"phone_number":"26266262","weight":42,"description":"das","created_at":"2015-03-04T18:50:23.924+02:00","updated_at":"2015-03-04T18:50:23.924+02:00","in_blacklist":false,"admin_confirmed":false,"vip":false,"identifier":"42179","expiration":"2015-04-29T18:50:23.926+03:00","smsidentifier":null,"highlight":"2015-03-04T18:50:23.926+02:00","recomend":"2015-03-04T18:50:23.927+02:00","vip_highlight":"2015-03-04T18:50:23.927+02:00","vip_recomend":"2015-03-04T18:50:23.927+02:00","prolong":null,"description_ru":"dasdad","work1":"2","work2":"3","work3":"7","work4":"17","email":"dasd66666@dsdsadas.lv","can_add_review":true,"can_show_recomended":true,"paid":false,"token":"","user_id":null}
我查了一下,广告创建成功,但是为什么这个奇怪的重定向只发生在广告上?也不是消息吗?
任何帮助都会很棒。 提前致谢。
最佳答案
我会在你的脚本上使用jquery捕获成功和错误事件我会尝试这样的事情:
if @advertisement.save
format.html { redirect_to @advertisement, notice: 'advertisement was successfully sent.' }
format.js
else
format.html { render action: 'new' }
format.json { render status: :500 } //Set the error right now so you can catch it later on your script
根据您的需要,您也可以这样做
if @advertisement.save
format.html { redirect_to @advertisement, notice: 'advertisement was successfully sent.' }
format.js, alert: "your success message"
else
format.html { render action: 'new' }
format.json { render nothing: true }, alert: "your error message" // so you don't have to catch any errors on the script
在你的脚本中只需使用 jquery 来管理 AJAX
$.ajax({
type: "POST",
url: "THE URL YOU ARE POSTING TO",
dataType: "json",
});
关于javascript - 无法使用 Ajax、Rails 4 提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28860276/