2016-11-26 53 views
0

如何使用jQuery在列表中顯示json數據?jQuery json顯示在列表中

$(document).ready(function() { 
 

 

 
$.getJSON('example.json', function(data) { 
 

 
    $.each(data.example, function(key, value) { 
 
       
 
       var output=""; 
 
       output="<li>" + data.example[key].name + "</li>"; 
 

 
       $('#example').append(output); 
 
       
 
    }); 
 

 
     }); 
 
      }

這似乎並沒有顯示任何內容。

+2

你需要:1)你的問題的一個更好的格式; 2)編寫你使用的完整代碼。 –

+0

剛剛添加的代碼 – Rebekah

+0

對不起系統搞砸了,不會讓我添加代碼 – Rebekah

回答

1
$(document).ready(function() { 
    $.getJSON('example.json', function(data) { 
     var output = ''; 
     $.each(data.example, function(key, value) { 
      output += '<li>' + value.name + '</li>'; 
     }); 
     $('#example').html(output); // <ul id="example"></ul> 
    }); 
}); 

UPDATE:工作JSON文件

{ 
    "example": [ 
     { 
      "name": "Dr. Sammie Boyer", 
      "email": "[email protected]" 
     }, 
     { 
      "name": "Eladio Beier", 
      "email": "[email protected]" 
     }, 
     { 
      "name": "Hilton Borer", 
      "email": "[email protected]" 
     } 
    ] 
} 
+0

呃還是不行的 – Rebekah

+0

控制檯是否顯示有錯誤? – Wizard

+0

不會難過它不會 – Rebekah

0

您有幾個語法錯誤。每個函數中的逗號都是錯誤的,並且沒有關閉);最後。下面的代碼應能正常工作......

$(document).ready(function() { 


$.getJSON('example.json', function(data) { 

    $.each(data.example, function(key, value) { 

       var output=""; 
       output="<li>" + data.example[key].name + "</li>"; 

       $('#example').append(output); 

    }); 

     }); 
      }); 
+0

而不是使用'data.example [關鍵] .name'你可以使用'value.name' - 的,而是在每次迭代追加的循環,我會連接字符串,並且只能在循環後追加以提高性能。 – ochi

+0

我該怎麼做? – Rebekah

+0

@Rebekah看看精靈的回答 – ochi

0

這將是我服食。

您有多個語法錯誤(這是很難看到,因爲代碼格式不) - 格式化代碼可以幫助你看到這些錯誤。

注:我做避免了AJAX調用來獲取JSON數據的循環解析例子。

$(document).ready(function() { 
 
    var data = { 
 
    "example": [{ 
 
     "name": "Dr. Sammie Boyer" 
 
    }, { 
 
     "name": "Eladio Beier", 
 
     "email": "[email protected]" 
 
    }, { 
 
     "name": "Hilton Borer", 
 
     "email": "[email protected]" 
 
    }] 
 
    }; 
 

 
    
 
    
 
// we don't have to get the json in an AJAX call for this demo 
 
// $.getJSON('example.json', function(data) { 
 
     var output = "<ul>"; 
 
    
 
     $.each(data.example, function(key, value) { 
 
     output += "<li>" + value.name + "</li>"; 
 
     }); 
 
     
 
     output += "</ul>"; 
 
     $('#example').append(output);; 
 
// }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="example"></div>