【发布时间】:2014-05-18 01:32:45
【问题描述】:
Soo,我有这个验证,我正在尝试使用 AJAX 和 Coffee Script 获取请求进行设置。此请求调用 RoR 控制器上的方法,并假设发送回数据。但是,它不起作用。这是我第一次参加 Coffee Script,所以请温柔一点,我只是个婴儿。
我的错误 -> ActionController::RoutingError (没有路由匹配 [GET] "/home/get_email/test@test.com"):
我需要为我的 AJAX GET 请求创建路由吗?代码如下。
假设 .change 函数完成了它的工作并进入了我的 AJAX cal l 符合预期。
###Coffee 脚本 AJAX###
jQuery ->
$('#txt_email').blur ->
@data
@txtemail = $('#txt_email').val()
$.ajax 'home/get_email/' + @txtemail,
type: "GET",
dataType: "JSON",
asnyc: false,
success: (data) ->
console.log(data)
###Home 控制器方法###
def get_email(email)
@db_email = User.where(["email = ?", email]).first
respond_to do |format|
if @db_email != nil
format.js {}
format.json { render json: @db_email }
else
format.html { render action: 'index' }
format.json { render json @db_email.email, status: :unprocessable_entity }
end
end
end
取得一些进展。目前这是正在发生的事情。似乎没有填充 id 参数,但“电子邮件”文本值正在通过。我还更新了 Coffee JS 以正确传递 txt_email 值。
Parameters: {"email"=>"test@test.com", "id"=>"get_email"}
Animal Load (1.0ms) SELECT "animals".* FROM "animals" WHERE "animals"."id" = ? LIMIT 1 [["id", "get_email"]]
###路线###
home_index GET /home/index(.:format) home#index
home_show GET /home/show(.:format) home#show
profile_new GET /profile/new(.:format) profile#new
root GET / home#index
GET /home(.:format) home#index
POST /home(.:format) home#create
new_home GET /home/new(.:format) home#new
edit_home GET /home/:id/edit(.:format) home#edit
home GET /home/:id(.:format) home#show
PATCH /home/:id(.:format) home#update
PUT /home/:id(.:format) home#update
DELETE /home/:id(.:format) home#destroy
profile_index GET /profile(.:format) profile#index
POST /profile(.:format) profile#create
new_profile GET /profile/new(.:format) profile#new
edit_profile GET /profile/:id/edit(.:format) profile#edit
profile GET /profile/:id(.:format) profile#show
PATCH /profile/:id(.:format) profile#update
PUT /profile/:id(.:format) profile#update
DELETE /profile/:id(.:format) profile#destroy
这里是完整的解决方案
最终代码
$(txtemail).blur ->
if theEmailIsRegistered($(this).val()) is false
$('#lbl_error_email').html('The entered e-mail is already in use.')
else
$('#lbl_error_email').html('')
theEmailIsRegistered = (email) ->
$.ajax 'home/get_email/',
type: 'GET',
dataType: 'JSON',
data: {email: email }
async: false,
success: (data) ->
if data is true
return true
else
return false
def get_email()
@db_email = User.where(email: params[:email]).first
respond_to do |format|
if @db_email.present? && @db_email.email == params[:email]
format.js {}
format.json { render json: true }
else
format.js
format.json { render json: false }
end
end
end
自定义路线
get 'home/get_email' => 'home#get_email'
【问题讨论】:
标签: ruby-on-rails ruby ajax coffeescript