如何使 AJAX 响应从 Rails 端工作? [英] How to make AJAX responses work from the Rails side?

查看:33
本文介绍了如何使 AJAX 响应从 Rails 端工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML 表单:

<form id="newsletter" method="post" action="/subscribers" data-remote="true">
    <label for="email">Enter your email:</label>
    <input type="text" name="email" class="text" />
    <p class="btn"><span>Signup</span></p>
</form>

注意data-remote="true"

控制器:

class SubscribersController < ApplicationController
  def create
    @subscriber = Subscriber.create(:email      => params[:email],
                                    :ip_address => request.remote_ip )

    respond_to do |format|
      format.js
    end
  end
end

视图(订阅者/create.js.erb)

no clue what goes here to make it return normal AJAX response (or error if it encountered one

1.我在视图中放了什么才能让它返回正常的 ajax 响应或错误? -- 是否甚至需要开始(我可以在不创建此类视图的情况下返回它)

1. What do i put in the view to make it return normal ajax response or error? -- Is it even needed to begin with (can I return this without creating such views)

2.这是用 Rails 做 ajax 的正确方法吗?

推荐答案

这看起来与我今天刚刚为另一个用户回答的问题完全一样......相同的型号名称和所有内容.

This looks exactly like a question that I just answered today for another user... same model names and everything.

def create
  @subscriber = Subscriber.new(#your params)
  respond_to do |format|
    if @subscriber.save
      format.js { render :json => @subscriber, :status => :created, :location => @susbscriber }
    else
      format.js { render :json => @susbcriber.errors, :status => :unprocessable_entity }
    end
  end
end

此外,您不必在控制器中执行unless Subscriber.find_by_email(params[:email]).您应该将 validates_uniqueness_of :email 添加到订阅者模型.

Also, you shouldn't have to do the unless Subscriber.find_by_email(params[:email]) in your controller. You should just add validates_uniqueness_of :email to the Subscriber model.

在包含表单的 .erb 文件中,您将添加以下 javascript:

In the .erb file that contains the form, you would add the following javascript:

jQuery(function($) {
  // create a convenient toggleLoading function
  var toggleLoading = function() { $("#loading").toggle() };

  $("#your-form")
    .bind("ajax:loading",  toggleLoading)
    .bind("ajax:complete", toggleLoading)
    .bind("ajax:success", function(event, data, status, xhr) {
      $("#response").html(data);
    });
    .bind("ajax:failure", function(event, data, status, xhr) {
      //your code
    });
});

这篇关于如何使 AJAX 响应从 Rails 端工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆