简体   繁体   中英

Issues loading a JSON file using jQuery and AJAX in PHP

Trying to load the content from a JSON file using jQuery and AJAX in PHP but the function is only returning [object Object],[object Object],[object Object] .

Here is the JSON file.

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

Here is the code I am using.

<!DOCTYPE html>
<html>

<head>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("button").click(function() {
                $.ajax({
                    url: 'testing.txt',
                    type: 'GET',
                    dataType: 'json',
                    success: function(result) {
                        alert(result['employees']);
                    },
                    error: function() {
                        alert("error");
                    }
                });
            });
        });
    </script>
</head>

<body>
    <div id="div1">
        <h2>Let jQuery AJAX Change This Text</h2>
    </div>
    <button>Get External Content</button>
</body>

</html>

What am I doing wrong?

Try the following to display you json to the page:

You use the dot selector to select the values of the fields based on the property name,for the employees property is al little different because we have a array, so we loop through it

success: function(result) {
     $('#div1').empty();
     $.each(result.employees,function(i,v){
        $('#div1').append('<h2>'+v.firstName+' - '+v.lastName+'</h2>');
     });

},

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