简体   繁体   中英

I am developing a website in which i want to read some json file locally in my js file

data = {"items": [
                   {
                        "title": "sample 1",
                        "author": "author 1"
                   },
                   {
                        "title": "sdample 2",
                        "author": "author 2"
                   }
]};

This is my json file.

Now I want to read this local json file in my js to print the values of json in HTML page I dont want to use any httpsRequest.

NOTE: I am not using any web server

Below is my JS file

 function data(languageClass){ var news = document.getElementsByClassName(languageClass)[0]; var item = json.items;// where json is local json copy which i want console.log( "hiiii" + item); for(var i = 0; i < item.length; i++) { var h5 = document.createElement("h5"); h5.innerHTML = item[i].title; news.appendChild(h5); var p = document.createElement("p"); p.innerHTML = item[i].author; news.appendChild(p); } } 

below is my HTML file :

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
 <script type="text/javascript" src="D:/Shubhankar/web/quess.json"></script> 
<script type="text/javascript"
    src="../web/Question.js"></script>

<title>Java Interview Question</title>
<link rel="icon" type="image/png" href="../img/icon.png">
</head>
<body onload='data("interviewQuestions")'>

    <div class="interviewQuestions"></div>
</body>
</html>
data = {"items": [
                         {
                           "title": "sample 1",
                           "author": "author 1"
                         },
                         {
                          "title": "sdample 2",
                          "author": "author 2"
                         }
]};

This is not a valid JSON.

Without web server or XHR request, you cannot load your data. One way to get this data in your app is to have a JS file with JSON content in it. Sample:

var data={"items": [
    {
      "title": "sample 1",
      "author": "author 1"
    },
    {
      "title": "sdample 2",
      "author": "author 2"
    }
  ]
}

Now call this JS file using script tag.

<script src="path/to/jsonfile.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM