2017-04-10 109 views
0

我正在練習Ajax調用,並且在訪問返回的JSON數據時遇到問題。用jquery操縱json數據

我有以下

$('button').on('click', function() {  
    $.ajax({ 
    url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1', 
    success: function(data) { 
     console.log(data); 
    }, 
    error: function() { 
     console.log('error occured'); 
    }, 
    cache: false 
    }); 
}); 

下面的代碼輸出

[ 
{ 
"ID": 1127, 
"title": "Paul Rand", 
"content": "<p>Good ideas rarely come in bunches. The designer who voluntarily presents his client with a batch of layouts does so not out prolificacy, but out of uncertainty or fear. </p>\n", 
"link": "https://quotesondesign.com/paul-rand-7/" 
} 
] 

我只是想給我的輸出JSON對象的contentlink性能。我已經試過如下:

$('.message').html(JSON.stringify(data)); 

其輸出

[{"ID":2294,"title":"Josh Collinsworth","content":" 
You do not need to have a great idea before you can begin working; you need to begin working before you can have a great idea. 

\n","link":"https://quotesondesign.com/josh-collinsworth-3/"}] 

我試圖尋找標準的方法來處理JSON數據,感謝所有幫助!

回答

3

顧名思義,stringify將JSON轉換爲字符串。 JSON是本地JavaScript,並根據您的樣本數據:

[ 
    { 
     "ID": 1127, 
     "title": "Paul Rand", 
     "content": "<p>Good ideas rarely come in bunches. The designer who voluntarily presents his client with a batch of layouts does so not out prolificacy, but out of uncertainty or fear. </p>\n", 
     "link": "https://quotesondesign.com/paul-rand-7/" 
    } 
] 

你回來對象數組(方括號中)(在大括號)在這種情況下,它在陣列中只有一個對象,所以你與data[0]訪問數組中的第一個對象,然後獲取其content屬性:

$('.message').html(data[0].content); 
+0

u能澄清指數0? –

+0

是的,我會編輯問題 – miken32

+0

啊。我現在可以清楚地看到一切。謝謝您的幫助!!!使用API​​的工作已經很棒了! –