簡體   English   中英

為什么運行代碼時為什么我的json數據不會出現在瀏覽器中

[英]Why my json data wont appear in browser when i run the code

我的json數據不會出現在瀏覽器中。 這是我第一次使用json,我無法找出問題所在。我在互聯網上進行搜索,發現它與mime有關,但仍然無法解決。 這是代碼:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var jsonData = '[{"rank":"9","content":"Alon","UID":"5"},{"rank":"6","content":"Tala","UID":"6"}]';
$.ajax({
    url: '/echo/json/',
    type: 'POST',
     contentType:"application/json; charset=utf-8",
    data: {
        json: jsonData
    },
    success: function (response) {
        var trHTML = '';
        $.each(response, function (i, item) {
            trHTML += '<tr><td>' + item.rank + '</td><td>' + item.content + '</td><td>' + item.UID + '</td></tr>';
        });
        $('#records_table').append(trHTML);
    }
});
</script>
</head>
<body>
<table id="records_table" border='1'>
    <tr>
        <th>Rank</th>
        <th>Content</th>
        <th>UID</th>
    </tr>
</table>
</body>
</html>

這是更新的代碼

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var jsonData = '[{"rank":"9","content":"Alon","UID":"5"},{"rank":"6","content":"Tala","UID":"6"}]';
$(document).ready(function(){
$.ajax({
    url: '/echo/json/',
    type: 'POST',
     contentType:"application/json; charset=utf-8",
    data: {
        json: jsonData
    },
    success: function (response) {
        var trHTML = '';
        $.each(response, function (i, item) {
            trHTML += '<tr><td>' + item.rank + '</td><td>' + item.content + '</td><td>' + item.UID + '</td></tr>';
        });
        $('#records_table').append(trHTML);
    }
});


});
</script>
</head>
<body>
<table id="records_table" border='1'>
    <tr>
        <th>Rank</th>
        <th>Content</th>
        <th>UID</th>
    </tr>
</table>
</body>
</html>

您在ajax調用周圍缺少文檔就緒塊。

編寫一個Error方法,看看是否發生了一些ajax錯誤

`$.ajax({
   success: function(){
     // Handle the success event
   },
   error: function(xhr){
     // Handle the error event
   }
   // ......
 });`

xhr將顯示響應文本

更新:

您的代碼完全正確,就像nikhil所說的dodument.ready應該是魔術

檢查我用您的代碼測試過的小提琴http://jsfiddle.net/8sfm0p14/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM