2016-11-23 109 views
0

內使用javascript軌道創建我有在我創建外部events.json文件軌這種方法的文件。如何閱讀new.html.erb

def new 
     @event=Event.new 
     @users=User.all 
     @[email protected] 
     tempJson = @events.to_json.html_safe 
     aFile = File.new("events.json", "r+") 
     aFile.syswrite(tempJson) 
    end 

現在events.json文件在我的app目錄中創建。 在我new.html.erb,如何通過JavaScript訪問該文件,並將其設置爲一個變量?

<script type="text/javascript"> 
      $.getJSON("events.json", function(json) { 
     debugger; 
     console.log(json); 
     });  
    </script> 

我想這個..當我檢查我收到此錯誤信息,

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3000/users/14/events/events.json 
+1

爲什麼不把它渲染爲json的方法? – webster

+0

文件存儲位置的實際路徑是什麼?即它在哪個目錄中? – user2085143

+0

@ user2085143的events.json文件生成並存儲相同的應用程序目錄,其中的應用程序,bin等等目錄存在[畫面]內(https://drive.google.com/open?id=0B2BZFbohNopKT1FIOTlpNi1hVEE) –

回答

0

你必須將文件寫入公共/目錄下的location = "users/14/events/events.json"

使用。您可以通過執行實現這一目標:

File.new(Rails.public_path + 'events.json', 'w+') 

然後,您可以訪問該文件在您看來這樣做的:

$.getJSON("/events.json") 

,但我認爲最好的方式來實現這一目標是通過具有和EventsController在json中響應的索引操作。

class EventsController < ApplicationController 
    def index 
    @events = Event.all 
    respond_to do |format| 
     format.json { render json: @events} 
    end 
    end 
end 
+0

謝謝。我開始知道瀏覽器在public目錄中搜索events.json文件。現在它工作正常。 :) –

+0

更好的方式來獲取公共目錄,就像是用'Rails.public_path' @jrbedard答案。回答編輯。 – vl3

0

第一:你確定該文件寫的?因爲你用File.new("events.json", "r+")我認爲手段read你需要w+write

二:在兩種情況下Rails.public_path + path + /file