我正在通过 Twitter 引导模式窗口传递一个 ajax 调用来更新我的应用程序中的数据。 ajax代码如下:
$(document).ready(function(){
var link=$('#link_hash').val();
$("#update_link").click(function(){
console.log("I'm here");
$.ajax({
url: "profiles/update_link",
type: "POST",
dataType: "html",
data: {link: link,data: $('#link_hash').val() },
success: function(data) {
// some code
},
error: function(data1) {
// some code
}
});
});
});
我已经修改了 route.rb 文件以使其与我的 Controller “update_link”方法相匹配。 我的方法中的代码如下:-
def update_link
@link=Link.find_by_link(params[:link])
@tlink=Link.find_by_link(params[:data])
logger.info "=========kkkkkkkkkkkkkk=================================#{@link.inspect}"
logger.info "=========kkkkkkkkkkkkkk=================================#{@tlink.inspect}"
logger.info "=========kkkkkkkkkkkkkk=================================#{params.inspect}"
respond_to do |format|
if @tlink.nil?
@link.update_attributes(:link => params[:data])
...some code....
else
...some code...
end
end
end
end
所以在服务器日志中显示 -
Started POST "/profiles/update_link" for 127.0.0.1 at 2013-02-20 12:08:20 +0530
Processing by ProfilesController#update_link as HTML
Parameters: {"link"=>"9bfzjp", "data"=>"9bfzjpaaa"}
WARNING: Can't verify CSRF token authenticity
Completed 401 Unauthorized in 6ms
很明显 “logger.info” 没有显示...现在搜索后我能够解决警告但仍然存在 401...如何解决这个问题??
提前致谢....
最佳答案
根据您的服务器日志,您没有传递 CSRF token ,因此 Rails 会自动将请求视为恶意请求并将其标记为未验证。未经验证的请求的默认处理是重置 session 。您可以注释掉 protect_from_forgery
或将 skip_before_filter :verify_authenticity_token
添加到您的 Controller 以查看是否是这种情况吗?
如果您想在 ajax 请求中包含真实性 token (强烈推荐),您可以将其添加到 ajax 请求的 header 中:
headers: {
'X-Transaction': 'POST Example',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
关于ruby - 在 Rails 3 应用程序中调用 .ajax 方法时出现 401 Unauthorized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14975489/