我正在处理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