简体   繁体   中英

How to load a JSON file which is located in the same path?

I'm searching for a way to load a JSON file located in the same folder as the html and js files. The method should work no matter if the files are hosted on a web server or distributed for local offline usage.

I tried fetching the file with XMLHttpRequest but with offline usage this seems to work only with Firefox.

Any help would be appreciated!

There is no reliable, cross-browser way to write a webpage that can load files from the user's file system - even if the page is loaded from there.

Embed the JSON in JavaScript scripts instead.

You have two options here.

1) embed the JSON data in the js script.

or

2) use a small PHP file which gets the file content and brings it to the js script by using AJAX.

Loading file : data.json located in the same path as the html file, This might help u...

Path

|- index.html

|- data.json ( Json File )

<html>
<head>

    <title>Loading a Json using Jquery</title>

    <style>
        body{
            text-align: center;
            font-family: arial;
        }

        .button{
            margin:20px;
            font-size:16px;
            font-weight: bold;
            padding:5px 10px;
        }
    </style>


</head>
<body>
    <a href="data.json" target="_blank">Open JSON file</a><br />
    <input type="button" value="Get and parse JSON" class="button" />
    <br />
    <span id="results"></span>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

    <script>

        //When DOM loaded we attach click event to button
        $(document).ready(function() {

            //after button is clicked we download the data
            $('.button').click(function(){

                //start ajax request
                $.ajax({
                    url: "data.json",
                    //force to handle it as text
                    dataType: "text",
                    success: function(data) {

                        //data downloaded so we call parseJSON function 
                        //and pass downloaded data
                        var json = $.parseJSON(data);
                        //now json variable contains data in json format
                        //let's display a few items
                        $('#results').html('Plugin name: ' + json.name + '<br />Author: ' + json.author.name);
                    }
                });
            });
        });
    </script>

</body>
</html>

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