无法使用Ajax,Rails 4提交表单

时间:2015-03-04 16:55:11

标签: javascript jquery ruby-on-rails ajax forms

我有表格的广告和消息模型。两个表单都使用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}

我检查过,广告是成功创建的,但为什么这种奇怪的重定向只发生在广告上?还不是消息?

任何帮助都会很棒。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

我会在你的脚本上用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",
});