我正在處理jQuery和Rails 3.1之間的AJAX請求(現在,在localhost上工作,在Chrome和Firefox中測試,如果有幫助的話)。當用戶點擊鏈接時,我會將兩個文本字段的值傳遞給服務器。具體來說,我有一個名爲AnswersController的控制器,它將這兩個值存儲到「answers」數據庫表中。來自jQuery的AJAX請求在Rails處理中缺少參數
以下是我的前端代碼來提出請求。該請求被Rails成功接收,因爲此請求中的響應函數發生,並且我的段落名爲「last_chance」被服務器響應的內容填充。
$('.other_question a').click(function(e) {
var this_profile_id = window.location.pathname.substring(1).split('/')[1];
var this_question_id = window.location.pathname.substring(1).split('/')[3]; // there is a hidden space when splitting
var ajax_data = {
type : "PUT", /* should this be POST for older browsers? */
url : '/profiles/' + this_profile_id + '/answers/' + this_question_id + '.json',
contentType : 'json',
dataType : 'json',
success : function(msg) {
alert("Data Saved: " + msg);
$('#last_chance').text(msg['saved']);
},
data : {
_method : 'PUT',
page : {
authenticity_token : $('input[name=authenticity_token]').attr('value'),
answer : {
response : 'hi there',
comments : 'word'
},
action : 'update',
controller : 'answers',
profile_id : this_profile_id,
id : this_question_id
}
}
};
$.ajax(ajax_data);
return false;
});
這裏是我的後端代碼來處理這樣的:該方法是在AnswersController更新:
def update
respond_to do |format|
format.html { redirect_to 'http://google.com'}
format.json { render :json => {:saved => 'ok: ' + params.to_s }.to_json }
end
return
end
現在,當我填的是「last_chance」段落元素與Rails所收到的參數,可以它顯示以下內容:
ok: {"action"=>"update", "controller"=>"answers", "profile_id"=>"11", "id"=>"42", "format"=>"json"}
看來,除非事情已經發生了,我不知道的,Rails所不接受或接收我包含在AJAX調用這些其他參數。有人可以向我解釋爲什麼這是?我如何確保它收到所有包含的參數?
非常感謝您的幫助!
哦,另外:我刪除了所有的數據參數,並返回相同的結果(也就是說,我猜,Rails處理返回的參數)。但是,我怎麼才能傳遞數據呢?這些定製參數在哪裏去?
編輯:從響應的建議,我把它改成這樣:
params[:saved] = 'OK'
respond_to do |format|
format.html { redirect_to 'http://google.com'}
format.json { render :json => params.to_json }
end
由此,我在「last_chance」部分擁有的唯一的輸出是「OK」。我可以從哪裏出發?
嗨維克,感謝您的回覆。我試過這個,並把結果放在我的第一篇文章的編輯部分。看來,參數散列是空的。我可以從哪裏出發? – spanport 2012-04-02 12:37:13
如果參數哈希值爲空,而不是如何得到響應:ok:{「action」=>「update」,「controller」=>「answers」,「profile_id」=>「11」,「id」=>「42 「,」format「=>」json「}。只需調試參數並在添加新參數前後輸出其值[:saved] ='OK' 。並檢查你的日誌。 – Vik 2012-04-02 12:57:49
嗨維克 - 我想我也許在你對這部分的建議中做了一些不正確的改變。但是我改變了它,以便所有的數據都從「頁面」中移出來,並轉化爲「數據」本身,現在一切似乎都奏效了。感謝您的貢獻。 – spanport 2012-04-02 13:56:15