2011-11-19 121 views
0

我有這樣的側邊欄簡報註冊框:如何正確地處理Ajax並處理Rails中的部分表單錯誤?

-------------------------------- 
|     |   | 
|     |   | 
|     |__________| 
|     |NEWSLETTER| 
|     |   | 
|     |   | 
-------------------------------- 

我已經創建了以下行動newsletter_controller:

class SubscribersController < ApplicationController 
    def create 
    @subscriber = Subscriber.new(params[:subscriber]) 
    end 
end 

我感到困惑中軌的幾件事情:

1.如何用rails helpers編寫表單,並將其作爲AJAX請求發佈到此表單中?

2.如果用戶輸入的內容不是有效的電子郵件地址或空白,我該如何在表單字段旁邊的新聞快報側欄中寫出消息?

3.如果插入成功,我該如何用「您已註冊」消息來替換表單。

我是新來的rails和jquery。

回答

0

1)您需要閱讀有關處理表單和執行ajax帖子的rails和jquery API。前者可以在這裏找到:http://guides.rubyonrails.org/form_helpers.html 後者可以在這裏找到:http://api.jquery.com/jQuery.post/。在這兩個頁面上都有很好的例子

2)您將希望通過javascript在輸入上運行某種基本的正則表達式(以及當從rails發佈數據時)以驗證用戶輸入。這是另一個堆棧溢出帖子:jQuery Email Regex。這裏是一個使用它的例子:

var fakeEmailAddress = "[email protected]"; 
var emailRegex = /^[A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[A-Z]{2,6}$/i; 
var isAnEmailAddress = fakeEmailAddress.match(emailRegex); 
if (!isAnEmailAddress) { 
    alert("Yo bro. What's up with that email addy? Try again"); 
} 

3)在jquery ajax後,你可以設置「成功」功能來做到這一點。檢查#1中的鏈接。您可能希望爲表單提供一個ID屬性,並用您從該帖子中檢索到的html數據替換表單,如下面的計算器問題所示:why does this not work?? jquery ajax replace content in specific div