[英]Cant submit form using Ajax, Rails 4
我有帶有表格的廣告和消息模型。 兩種形式都使用Ajax( remote => true )提交。
郵件表格提交完美。 它停留在同一頁面並處理響應,但廣告形式則不然。 形式,控制器和腳本代碼都相同。 只是從消息變為廣告 ..
廣告形式。
<%= form_for(@advertisement, :html => {"data-parsley-validate" => true},remote: true, format: :json) do |f| %>
....
#lot of code here
....
<%end%>
廣告控制器:
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",
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.