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

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

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

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


        
7条回答
  •  梦毁少年i
    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.

    
    
    
    
    
    
    
    
    

    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/

提交回复
热议问题