我正在尝试编写一个Ajax调用,用于检查用户输入到表单中的电子邮件地址是否已经存在于数据库中。我检查并仔细检查了我的路线,但无法找出问题所在。有多个类似的SO问题,但其中大多数似乎是问题在于有人将路线定义为get
在routes.rb
中,但是使用post
进行了Ajax呼叫,反之亦然。那我得到的错误是:POST http://localhost:3000/registrations/validate_uniqueness 404 (Not Found)
Ajax调用在Rails 3.2应用程序中404/500错误(路由选中)
routes.rb
post '/registrations/validate_uniqueness' => 'registrations#validate_uniqueness'
...
registrations_controller.rb
def validate_uniqueness
if User.find_by_email(params[:email])
render :json => { value: true }
else
render :json => { value: false }
end
end
...
Ajax call, when successful should assign a boolean value to the `exists` variable
function validateUserFields() {
$.ajax({
type: "POST",
url: "/registrations/validate_uniqueness",
dataType: "json",
data: {email: $("#user_email").val()},
success: function() {
var exists = value;
alert(value);
},
error: alert("Error!")
})
...
更新 我改变了控制器动作看像这样:
def validate_uniqueness
respond_to do |format|
format.json do
if User.find_by_email(params[:email])
render :json => { value: true }
else
render :json => { value: false }
end
end
end
end
仍然得到404错误
第二个编辑 想出了如何使用Chrome的开发工具,看看我的Ajax请求的详细信息。这是完整的错误消息,从设计:
Unknown action
Could not find devise mapping for path "/registrations/validate_uniqueness".This may happen for two reasons:1) You forgot to wrap your route inside the scope block. For example: devise_scope :user do get "/some/route" => "some_devise_controller" end2) You are testing a Devise controller bypassing the router. If so, you can explicitly tell Devise which mapping to use: @request.env["devise.mapping"] = Devise.mappings[:user]
因此,我改变routes.rb
到:
devise_scope :user do
post '/registrations/validate_uniqueness' => 'registrations#validate_uniqueness'
end
这是朝着正确方向迈出的一步,但现在我越来越:
Uncaught ReferenceError: value is not defined
您在validate_uniqueness方法中忘记了'end'子句。干杯! – emaxi 2014-10-27 21:52:20
是的,刚刚注意到并添加了第四个'end'。仍然收到错误! – sixty4bit 2014-10-27 21:54:17
您可以打印本地Web服务器日志记录输出吗?你如何开始你的应用程序? – emaxi 2014-10-27 21:57:21