2012-08-03 90 views
1

我試圖加載json文件的按鈕點擊。它從來沒有達到成功的功能。 我認爲我可以在本地加載json文件,而不必在服務器上加載它? 爲什麼這不起作用。從本地目錄加載json

$(function(){ 
    $('.demo').click(function(){ 

      $.ajax({ 
      url: 'data/demo.json', 
      dataType: 'json', 
      success: function(data){ 
       console.log("data = ", data) 
         } 
     }); 

    }); 
}); 

這裏是我的文件夾結構樹。

  • 的index.html
  • 數據(文件夾)
    • demo.json JS
  • page.js

JSON

{"markers": [ 
     { 
      "point":new GLatLng(40.266044,-74.718479), 
      "homeTeam":"Lawrence Library", 
      "awayTeam":"LUGip", 
      "markerImage":"images/red.png", 
      "information": "Linux users group meets second Wednesday of each month.", 
      "fixture":"Wednesday 7pm", 
      "capacity":"", 
      "previousScore":"" 
     }, 
     { 
      "point":new GLatLng(40.211600,-74.695702), 
      "homeTeam":"Hamilton Library", 
      "awayTeam":"LUGip HW SIG", 
      "markerImage":"images/white.png", 
      "information": "Linux users can meet the first Tuesday of the month to work out harward and configuration issues.", 
      "fixture":"Tuesday 7pm", 
      "capacity":"", 
      "tv":"" 
     }, 
     { 
      "point":new GLatLng(40.294535,-74.682012), 
      "homeTeam":"Applebees", 
      "awayTeam":"After LUPip Mtg Spot", 
      "markerImage":"images/newcastle.png", 
      "information": "Some of us go there after the main LUGip meeting, drink brews, and talk.", 
      "fixture":"Wednesday whenever", 
      "capacity":"2 to 4 pints", 
      "tv":"" 
     }, 
] } 

回答

1

那麼我有一個類似的腳本,它訪問本地文件並且工作正常。我在這裏看到的問題是您的JSON無效。也許這就是問題所在?

+0

好吧,很高興知道,因爲其他人在這裏說你不能。你能給我一個有效的json文件,以便我可以測試。我從網上抓取這個作爲測試人員,所以我推測這是有效的。 – Chapsterj 2012-08-03 17:16:22

+0

通過http://jsonlint.com/運行它。錯誤是「點」:newGLatLng(40.294535,-74.68201)行。他們需要被雙引號包圍。如果有一個函數改變這些值,它會工作,但如果你使用它作爲一個靜態文件,它將永遠不會工作。 – 2012-08-03 17:18:59

+0

謝謝Dean的工作。我很高興你澄清了你實際上可以在本地加載json。 – Chapsterj 2012-08-03 17:40:31

0

即使頁面是通過文件在本地提供的,也不能使用AJAX訪問本地文件

+0

好的,你能給我一個如何加載這個文件的例子嗎? – Chapsterj 2012-08-03 16:56:40

+0

@JuanMendes除AJAX外,還有其他訪問本地文件的方法嗎? – Marcel 2013-02-14 20:18:23