简体   繁体   English

在PHP中使用jQuery和AJAX加载JSON文件时出现问题

[英]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] . 尝试在PHP使用jQueryAJAXJSON文件中加载内容,但是该函数仅返回[object Object],[object Object],[object Object]

Here is the JSON file. 这是JSON文件。

{"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: 尝试以下操作将json显示到页面:

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 您可以使用点选择器根据属性名称选择字段的值,因为由于我们有一个数组,所以employees属性几乎没有什么不同,因此我们遍历该数组

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

},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM