2016-07-29 114 views
0

試圖使用jQueryAJAXPHP中加載JSON文件中的內容,但該函數僅返回[object Object],[object Object],[object Object]在PHP中使用jQuery和AJAX加載JSON文件的問題

這裏是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> 

我在做什麼錯?

+0

嘗試提醒結果,看看是否它的對象,它是正確的,你有3個對象 –

+0

這是正確的,'result'是一個對象,而'result.employees'是一個數組三個對象...問題是你如何訪問數據...'result.employees [0] .firstName'將* John *例如 –

+0

@JaromandaX啊,這很有道理。謝謝! – TheAuzzieJesus

回答

1

請嘗試以下方法JSON顯示你的頁面:

可以使用點選擇器選擇基於屬性名稱字段的值,爲員工屬性是人有點不同,因爲我們有一個數組,所以我們遍歷它

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

}, 
+0

啊,這工作。謝謝! – TheAuzzieJesus

+0

不要忘記檢查綠色按鈕來接受答案:p – madalinivascu