0
我正在編寫一個應用程序,主要是通過AJAX調用後端服務器的UI。非常少的頁面加載。例如,當我創建旅程時,我的JS只是發送一個JSON對象給Padrino(通過POST),Padrino保存旅行對象(通過ActiveRecord)並返回一個JSON響應。如何清理Padrino AJAX調用?
它似乎工作,但我不想清理代碼,但我想清理提交的值。
這裏是我的POST
代碼(trips controller
)
post :index, :provides => :json do
response = {}
response[:trip] = {}
begin
@trip = Trip.new
@trip.title = params[:trip][:title]
@trip.description = params[:trip][:title]
if @trip.save
response[:status] = "Success"
response[:trip] = {:title => @trip.title, :description => @trip.description}
response[:message] = "#{@trip.title} successfully saved"
else
response[:status] = "Error"
response[:message] = "Error saving trip"
end
rescue
response[:status] = "Error"
response[:message] = "Error saving trip"
end
response.to_json
end
目前,只有兩個字段(標題和描述),但做的時候會有大約4-8。我不喜歡我如何構建新的旅程對象。
我試着使用:
@trip = Trip.build(params[:trip])
,但沒有奏效。
這裏是我的JS代碼發送POST:
// Save new trip
$("#new_trip_save_btn").click(function() {
var self = this;
var new_trip = get_new_trip();
$.ajax({
data: {trip:new_trip},
dataType: "json",
url: "/trips",
type: "post",
success: function(res) {
console.log(res)
}
});
});
......
var get_new_trip = function() {
var self = this;
var trip = {};
trip.title = $("#new_trip_title").val();
trip.description = $("#new_trip_description").val();
trip.departure_date = $("#new_trip_departure").val();
trip.return_date = $("#new_trip_return").val();
return trip;
}
所以我能做些什麼來清理代碼(POST操作刪除冗餘),並確保文本保存前消毒。
感謝
感謝您的答覆。然而,我的邏輯是用nginx渲染靜態頁面,並簡單地使用Padrino作爲後端。我將花費很多時間在JS UI上,所以沒有JS意味着無法訪問。有些人不喜歡。但是來吧...它是2012年。你有什麼想法用Backbone替換我的自定義JS ajax帖子? – cbmeeks 2012-04-19 12:33:13
取決於,骨幹是一個不錯的選擇,但如果應用程序邏輯不那麼複雜,可以更好地從頭開始寫幾行js。我的代碼'live'使用'data-remote'屬性觀察所有表單並將其轉換爲ajax請求。這是一個'標準的'rails-ujs/padrino-ujs調用,它總是有用的。 – DAddYE 2012-04-19 12:58:34
關於Backbone非常真實。我實際上是在nginx將要提供的一個HTML頁面中渲染index/new/edit表單。然後,我根據您正在嘗試做的事情來隱藏每個部分。使其顯示頁面加載是即時的。 :-) – cbmeeks 2012-04-19 13:07:07