2017-10-13 19 views
0

下面的代碼在我的分支上工作得很完美(甚至還有一些提交之前)和神祕的我現在得到了js消息:401(未授權)我檢查瀏覽器。Ajax調用不再工作(401未授權)

我有一個自動完成表單,當用戶選擇一個字段時,它需要發送這個數據,以便通過來自同一個控制器的動作「get_location」進行分析。

home_form.js

$(document).ready(function() { 
    return $("#search_city").on("change", function() { 
    return $.ajax({ 
     url: "home/get_location", 
     type: "GET", 
     dataType: "script", 
     data: { 
     city: $('#search_city').val() 
     } 
    }); 
    }); 

的routes.rb

resources :home, only: [:index] do 
    get 'get_location', on: :collection 
    end 

home_controller.rb

require 'recognize_data' 

class HomeController < ApplicationController 
    layout "home" 
    skip_before_action :authenticate_user!, only: [ :index ] 
    include DataX 

    def index 
    end 

    def get_location 
    # do some stuff here 
    end 

end 

home.html.erb

<!DOCTYPE html> 
<html> 
    <head> 
    <title></title> 
    <%= csrf_meta_tags %> 
    <%= action_cable_meta_tag %> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
    <%= stylesheet_link_tag 'home/manifest.css', media: 'all' %> 
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> 
    <link href='http://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'> 
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB5LELGIW21xr6W1H1NBQNvjqLM3hENa64&libraries=places&language=pt-BR"></script> 
    <%= javascript_include_tag 'home/manifest.js' %> 
    </head> 

<body> 

<%= yield %> 

<%= yield(:form_js) %> 

</body> 
</html> 
+2

聽起來像你需要進行身份驗證。也許你的認證令牌被緩存了,現在它被清除了。 – zsawaf

+0

您是否使用SPA方法,或者它只是來自平均多頁驗證的ajax調用?簡而言之,您是否使用令牌進行身份驗證或使用標準Cookie? – AntonTkachov

+0

@zsawaf我該如何解決它? –

回答

0

我有兩個問題,我的代碼:

1 - 是的,我忘了把最後});關閉js函數

$(document).ready(function() { 
    return $("#search_city").on("change", function() { 
    return $.ajax({ 
     url: "home/get_location", 
     type: "GET", 
     dataType: "script", 
     data: { 
     city: $('#search_city').val() 
     } 
    }); 
    }); 
}); 

2 - 我在home_controller上使用skip_before_action :authenticate_user!, only: [:index],並導致與get_location動作衝突。所以我從索引中刪除了限制,並且只留下了句子:skip_before_action :authenticate_user!以涵蓋所有的操作。