2012-08-03 89 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