JSON+Javascript/jQuery. How to import data from a json file and parse it?

前端 未结 7 1999
猫巷女王i
猫巷女王i 2021-01-31 19:12

If I have a JSON file named names.json with:

{\"employees\":[
    {\"firstName\":\"Anna\",\"lastName\":\"Meyers\"},
    {\"firstNam         


        
相关标签:
7条回答
  • 2021-01-31 19:58

    In the jQuery code, you should have the employees property.

    data.employees[0].firstName
    

    So it would be like this.

    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
    </head>
    <body>
    <script type="text/javascript">
        $.getJSON("names.json", function(data) {
            console.log(data);
            $('body').append(data.employees[0].firstName);
        });
    </script>
    </body>
    </html>
    

    Of course you'll need that property for the non jQuery version too, but you'd need to parse the JSON response first.

    Also keep in mind that document.write is destroying your entire page.


    If you're still having trouble, try the full $.ajax request instead of the $.getJSON wrapper.

        $.ajax({
            url: "names.json",
            dataType: "json",
            success: function(data) {
                console.log(data);
                $('body').append(data.employees[0].firstName);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log('ERROR', textStatus, errorThrown);
            }
        });
    

    http://api.jquery.com/jquery.ajax/

    0 讨论(0)
提交回复
热议问题