2016-06-08 82 views
0

我正在使用一些網站中的API生成隨機引號的網頁上工作。我試圖使用AJAX/jQuery來訪問由API提供的JSON。我嘗試過一百萬種不同的東西,但對於我來說,我無法通過ID來訪問JSON的值。我可以訪問整個JSON。但我似乎無法獲得個人價值觀。無法訪問單個JSON值/ jQuery-Ajax

此代碼...

function init() { 
var $data = $('#data'); 

$.ajax({ 
    url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous', 
    type: 'GET', 
    datatype: 'json', 
    success: function(data) { 
    $.each(JSON.parse(data),function(i, quote) { 
     $data.append('<p class="text-center"> '+quote+ '</p>'); 
    }); 
    }, 
    error: function(err) { alert(err); }, 
    beforeSend: function(xhr) { 
    xhr.setRequestHeader("X-Mashape-Authorization""); 
    } 
    }); 
} 
window.onload = init; 

這是回饋所有的值,他們是正確的格式。但是它會讓所有人都回歸。我不想要最後一個,我希望能夠通過ID分別訪問每個值。

{ 
    "quote": "Once you eliminate the impossible, whatever remains, no matter how improbable, must be the truth.", 
    "author": "Sherlock Holmes", 
    "category": "Famous", 
} 

以上是JSON的樣子。我只想訪問前兩個值。當過我嘗試的東西,如訪問他們...

$.ajax({ 
    url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous', 
    type: 'GET', 
    datatype: 'json', 
    success: function(data) { 
    document.write('<p>' + data.quote + '</p>'); 
    }, 
    error: function(err) { alert(err); }, 
    beforeSend: function(xhr) { 
    xhr.setRequestHeader("X-Mashape-Authorization", ""); 
    } 
}); 

我試過一百萬個不同的事情,但無論我做什麼,我不能用自己的ID獲得訪問JSON的值。這是我絕對第一次使用Web API,所以我必須錯過一些東西。任何幫助,將不勝感激。

+0

有沒有在你的問題的JSON額外的逗號和也'xhr.setRequestHeader一個額外的引號( 「X-Mashape的授權」「);' 嘗試https://jsonformatter.curiousconcept.com/和HTTP ://www.jslint.com/驗證你的代碼 – Jaumzera

+0

在頁面加載後你不能使用'document.write' ....它會把整個頁面中的所有內容都擦掉 – charlietfl

回答

0

做這樣的工作?

... 
success: function(data) { 
    var items = JSON.parse(data); 
    $data.append('<p class="text-center"> '+ items[0].quote + '</p>'); 
}, 
... 
+0

JSON.parse不需要'dataType:'json'' – charlietfl

+0

非常感謝你!這個工作。我所要做的只是和你的建議有一點不同,就是在items.quote中放下[0]。現在我可以訪問每個值它是自己的,並且以它的方式來做......當然是在我的能力範圍內:)再一次,非常感謝你,你真的讓我在這裏脫身了! –

+0

很高興工作! – H77