【发布时间】:2014-12-23 05:04:31
【问题描述】:
我正在尝试编写一个 Ajax 调用来检查用户输入到表单中的电子邮件地址是否已经在数据库中。我已经检查并仔细检查了我的路线,但无法找出问题所在。有多个类似的 SO 问题,但在大多数问题中,问题似乎是有人在routes.rb 中将路由定义为get,但使用post 进行了Ajax 调用,反之亦然。我得到的错误是:POST http://localhost:3000/registrations/validate_uniqueness 404 (Not Found)
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 请求的更多信息。这是来自 Devise 的完整错误消息:
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。仍然出现错误! -
您能打印本地 Web 服务器的日志输出吗?你如何启动你的应用程序?
-
刚刚将该输出添加到帖子的末尾
-
是的,进行了更改。现在我在处理响应或其他事情时遇到了麻烦,因为它告诉我
value未定义(尝试在render json行期间定义我的控制器操作),并且response和result未定义
标签: jquery ruby-on-rails ajax validation http-status-code-404