簡體   English   中英

在PHP中使用jQuery和AJAX加載JSON文件時出現問題

[英]Issues loading a JSON file using jQuery and AJAX in PHP

嘗試在PHP使用jQueryAJAXJSON文件中加載內容,但是該函數僅返回[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顯示到頁面:

您可以使用點選擇器根據屬性名稱選擇字段的值,因為由於我們有一個數組,所以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