新的rails,所以請原諒noob問題。通過AJAX捕獲電子郵件遇到了一些麻煩。Rails - 使用AJAX創建方法和響應的問題
所需的功能: 我創建一個登陸頁面爲我的網站,我們捕捉到的電子郵件(「信息」 =對象/模型)。我想要異步捕獲電子郵件,然後向用戶顯示感謝信息。如果用戶輸入無效的電子郵件,我想讓他們輸入正確的電子郵件。
我得到的工作 我可以正確捕獲電子郵件並通過AJAX執行驗證。如果我輸入無效的電子郵件,然後點擊「提交」,它不會顯示在/ leads/index上。如果我輸入了無效的電子郵件,它會顯示在/ leads/index上。
我沒有工作 我還沒有想出如何得到任何形式的回覆返回給用戶。如果保存成功,我想要做的就是更改h3(class =「results」)元素的文本。
我的代碼
landing.html.erb:
<h3 class="results">Give us your e-mail and we'll send you an invite to beta when it's ready.</h3>
<%= form_for(:lead, remote: true, :url => {:controller => 'leads', :action => 'create'}, :html => {:class => 'form-inline emailForm'}) do |f| %>
<div class="form-group">
<%= f.label(:email, 'E-mail', class: 'sr-only') %>
<%= f.text_field(:email, {:id => 'submitEmail2', :class=> 'form-lg', :placeHolder => 'E-mail Address'}) %>
</div>
<%= submit_tag("Sounds Good", {:id => 'submitEmail2', :class => 'btn btn-success btn-lg'}) %>
<% end %>
leads_controller.rb
class LeadsController < ApplicationController
layout false
#respond_to :html, :js
def index
@leads = Lead.order("created_at ASC")
end
def show
end
def new
end
def create
@lead = Lead.new(lead_params) #Create a new object without form parameters
end
def edit
end
def delete
end
private
def lead_params
params.require(:lead).permit(:email)
end
end
create.js.erb
$('h3.results').html("");
//If I remove this code, it works
<% if @lead.save? %>
$("h3.results").html("Thank you! We'll let you know when it's ready."));
$('.emailForm').hide();
<% else %>
$("h3.results").html("Invalid E-mail. Please try again!"));
<% end %>
如果我刪除create.js.erb中的最後一段代碼,一切正常,並且h3中的文本被刪除。保存聲明有什麼問題?我是在保存在我的代碼的正確部分,還是應該在控制器中?
所有幫助表示讚賞!
您使用的術語不建議新手。你在其他地方有編碼經驗嗎? –
謝謝!在過去的幾年中,一堆不同語言的經驗讓人興奮不已。最後重新開始全職開發。 – CHawk
堅持用Rails,你會發展得相當遠我想! –