Проблемы с загрузкой JSON файла с помощью jQuery и AJAX в PHP

0 TheAuzzieJesus [2016-07-29 07:52:00]

Попытка загрузить контент из JSON файла с помощью jQuery и AJAX в PHP но функция возвращает только [object Object],[object Object],[object Object].

Вот файл JSON.

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

Вот код, который я использую.

<!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>

Что я делаю не так?

json javascript jquery ajax php


1 ответ


1 Решение madalinivascu [2016-07-29 07:58:00]

Попробуйте следующее, чтобы отобразить json на странице:

Вы используете селектор точек для выбора значений полей на основе имени свойства, поскольку свойство employee мало чем отличается, потому что у нас есть массив, поэтому мы прокручиваем его

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

},