在JQuery中加载本地json文件

时间:2018-02-16 03:25:54

标签: jquery json

初学者......我一直在尝试从这个主题的答案中采用不同的方法 但它们似乎都没有用。我看到这个问题已被问到很多,但不知怎的,我仍然无法找到答案。我想使用本地json文件,它与我的JavaScript和HTML文件位于同一文件夹中,因此我可以从其中的对象创建表,并能够从中添加或删除对象。正如您所知,评论的解决方案并不起作用。有帮助吗?

HTML文件:

<!DOCTYPE html>
<html>
    <head>

        <title>Page Title</title>
        <link rel="stylesheet" type="text/css" media="screen" href="CSS/style.css" />

    </head>
    <body>

            <button id="json">json</button>

        <!-- <script type="text/javascript" src="books.json"></script> -->
        <script src="jquery-3.2.1.js"></script>
        <script src="script.js"></script>

    </body>
</html>

JavaScript文件:

$(document).ready(function(){
    // var myBooks = JSON.parse(books);


        $(document).on('click', '#json', function (event) {

                // alert(myBooks[0].author);
                // alert(myBooks[0].title);
                // alert(myBooks[1].author);
                // alert(myBooks[1].title);
        });

});

我的books.json文件

[
    {
        "author": "Margaret Atwood",
        "title": "THE HANDMAID'S TALE"
    },
    {
        "author": "Ursula K. Le Guin",
        "title": "THE DISPOSSESSED"
    },
    {
        "author": "Mary Shelley",
        "title": "FRANKENSTEIN"
    },
    {
        "author": "Ursula K. Le Guin",
        "title": "THE LEFT HAND OF DARKNESS"
    },
    {
        "author": "Connie Willis",
        "title": "DOOMSDAY BOOK"
    },
    {
        "author": "Frank Herbert",
        "title": "DUNE"
    },
    {
        "author": "Maureen F. McHugh",
        "title": "CHINA MOUNTAIN ZHANG"
    },
    {
        "author": "Joe Haldeman",
        "title": "THE FOREVER WAR"
    },
    {
        "author": "Kate Wilhelm",
        "title": "WHERE LATE THE SWEET BIRDS SANG"
    },
    {
        "author": "Orson Scott Card",
        "title": "ENDER'S GAME"
    },
    {
        "author": "Daniel Keyes",
        "title": "FLOWERS FOR ALGERNON"
    }
] 

1 个答案:

答案 0 :(得分:-1)

试试这个:

$.getJSON("books.json", function(json) {
    console.log(json);
    //access your JSON file through the variable "json"
});