簡體   English   中英

getJSON警報未返回任何內容-數據問題?

[英]getJSON alert not returning anything - data issue?

我在讀取此數據時遇到問題:

看起來像這樣:

{
  "ok": true,
  "messages": [
    {
      "text": "moo",
      "username": "bot",
      "type": "message",
      "subtype": "bot_message",
      "ts": "1448226157.000008"
    },
    {
      "text": "boo",
      "username": "bot",
      "type": "message",
      "subtype": "bot_message",
      "ts": "1448225998.000007"
    }
  ],
  "has_more": true
}

這是代碼:

$.getJSON("https://slack.com/api/channels.history?token=xxxx&channel=C0E&pretty=1", function(result){
            $.each(result, function(i, field){
                $("div").append(field + " ");
            });
        });

我所得到的是

[對象對象] [對象對象]

如何使數據正確顯示?

假設:

  1. 那就是完整的JSON
  2. 您想遍歷消息

您的循環應更像:

$.each( result.messages,
  function( i, msg ) {
    $("div").append( msg.username + ": " + msg.text + " " );   
  }
);

(或您希望顯示的任何字段)

您的意思是這樣的:

 var data = `{"ok": true,"messages": [ { "text": "moo", "username": "bot", "type": "message", "subtype": "bot_message", "ts": "1448226157.000008" }, { "text": "boo", "username": "bot", "type": "message", "subtype": "bot_message", "ts": "1448225998.000007" } ], "has_more": true }`; $(function() { var result = $.parseJSON(data); $.each(result, function(i, item) { if (typeof item != "object") { alert(item); } else { $.each(item, function(i, obj) { alert(obj.ts); }); } }); }); 
   

小提琴示例: https : //jsfiddle.net/4v0x34b1/

暫無
暫無

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

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