Loading local JSON file

2018-12-31 07:08发布

I'm trying to load a local JSON file but it won't work. Here is my JavaScript code (using jQuery:

var json = $.getJSON("test.json");
var data = eval("(" +json.responseText + ")");
document.write(data["a"]);

The test.json file:

{"a" : "b", "c" : "d"}

Nothing is displayed and Firebug tells me that data is undefined. In Firebug I can see json.responseText and it is good and valid, but it's strange when I copy the line:

 var data = eval("(" +json.responseText + ")");

in Firebug's console, it works and I can access data.

Anyone have a solution?

21条回答
笑指拈花
2楼-- · 2018-12-31 08:10

Found this thread when trying (unsuccessfully) to load a local json file. This solution worked for me...

function load_json(src) {
  var head = document.getElementsByTagName('head')[0];

  //use class, as we can't reference by id
  var element = head.getElementsByClassName("json")[0];

  try {
    element.parentNode.removeChild(element);
  } catch (e) {
    //
  }

  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = src;
  script.className = "json";
  script.async = false;
  head.appendChild(script);

  //call the postload function after a slight delay to allow the json to load
  window.setTimeout(postloadfunction, 100)
}

... and is used like this...

load_json("test2.html.js")

...and this is the <head>...

<head>
  <script type="text/javascript" src="test.html.js" class="json"></script>
</head>
查看更多
萌妹纸的霸气范
3楼-- · 2018-12-31 08:11
$.ajax({
       url: "Scripts/testingJSON.json",
           //force to handle it as text
       dataType: "text",
            success: function (dataTest) {

                //data downloaded so we call parseJSON function 
                //and pass downloaded data
                var json = $.parseJSON(dataTest);
                //now json variable contains data in json format
                //let's display a few items
                $.each(json, function (i, jsonObjectList) {
                for (var index = 0; index < jsonObjectList.listValue_.length;index++) {
                      alert(jsonObjectList.listKey_[index][0] + " -- " + jsonObjectList.listValue_[index].description_);
                      }
                 });


             }
  });
查看更多
春风洒进眼中
4楼-- · 2018-12-31 08:13

$.getJSON is asynchronous so you should do:

$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});
查看更多
登录 后发表回答