如何在Pure Javascript中输入Wiki API

时间:2018-01-04 03:37:28

标签: javascript

我试图在Javascript中访问Wiki API。如果我输入URL然后获取数据,但如果我在Javascript函数中使用它,那么它不起作用。这是网址:

https://en.wikipedia.org/w/api.php?action=query&format=json&titles=New_York&prop=revisions&rvprop=content&callback=

我在JQuery中取得了成功,但我想知道如何在Javascript中提取。

任何帮助将不胜感激。

<div id="getw"></div>


var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&titles=New_York&prop=revisions&rvprop=content&callback=?";

function getText() {  
    var request = new XMLHttpRequest();  
    request.open("GET", url, true);  
    request.onreadystatechange = function () {  
        if (request.readyState == 4 && request.status == 200) {  
            var wdata = JSON.parse(request.responseText);  
            document.getElementById("getw").innerHTML = wdata.query.normalized[0];  
        }  
    }  
    request.send(null);
}

2 个答案:

答案 0 :(得分:0)

当您向网址添加&callback=?时,JQuery将使用JSONP而不是常规的XMLHttpRequest。阅读THIS以获得使用vanilla JS的JSONP的详细解释。

因此,您可以执行以下操作来模仿JQuery正在执行的操作:

&#13;
&#13;
// Instead of "&callback=?", use the function name of an actual callback.
// In this case it will be "&callback=apiCallback" which is declared below.
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&titles=New_York&prop=revisions&rvprop=content&callback=apiCallback";

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
document.body.appendChild(script);

function apiCallback(res) {
  document.getElementById("getw").innerHTML = JSON.stringify(res.query.normalized[0]);
}
&#13;
<div id="getw"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

<div id="getw"></div>

//Thanks again  1cgonza

var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&titles=New_York&prop=revisions&rvprop=content&callback=apiCallback";

var script = document.createElement('script');

script.setAttribute('type', 'text/javascript');

script.src = url;

document.head.appendChild(script);

function apiCallback(res) {
  document.getElementById("getw").innerHTML = JSON.stringify(res.query);
}