问题
How do I extract Title (List of metropolitan areas by population) from WIkipedia API(http://en.wikipedia.org/w/api.php?format=json&action=query&titles=List_of_metropolitan_areas_by_population&prop=revisions&rvprop=content&callback=?)
I was able to get data from Wikipedia but having trouble extract data from it.
function getJSONP(url, success) {
var ud = '_' + +new Date,
script = document.createElement('script'),
head = document.getElementsByTagName('head')[0] || document.documentElement;
window[ud] = function(data) {
head.removeChild(script);
success && success(data);
};
script.src = url.replace('callback=?', 'callback=' + ud);
head.appendChild(script);
}
getJSONP('http://en.wikipedia.org/w/api.php?format=json&action=query&titles=List_of_metropolitan_areas_by_population&prop=revisions&rvprop=content&callback=?', function(data){
console.log(data);
document.getElementById("output").innerHTML = data.query;
});
<div id="output">
Want to display article title here.
</div>
below is what it shows up in Console. How can I extract "from: "List_of_metropolitan_areas_by_population"" and display in front-end?

回答1:
You were trying to make the content of an HTML element a javascript object, which is why you saw the result you saw. What you want is the string, so you need to access the part of the object that will give you the string.
document.getElementById("output").innerHTML = data.query.normalized[0].from;
Instead of
document.getElementById("output").innerHTML = data.query;
Here's a link to the fiddle to go along with your answer: http://jsfiddle.net/zsaj950t/
回答2:
If you want to, for example, extract the "to: ..." then simply look at the object you have opened in Console. Simply change between "to" and "from" at the end of
data.query.normalized[0]
The changed code:
function(data){
document.getElementById("output").innerHTML = data.query.normalized[0].to
});
来源:https://stackoverflow.com/questions/30226255/javascript-extract-data-from-wikipedia-api