简体   繁体   English

从API记录响应

[英]Logging response from API

So, I've made this code that is supposed to scan an API for Wikipedia, and then use console.log to write all of the information from the API. 因此,我编写了此代码,该代码应扫描Wikipedia的API,然后使用console.log编写来自API的所有信息。 However, it's not returning anything. 但是,它没有返回任何东西。

function display() {
  $.get('https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Stack%20Overflow', function(Data){
    var elements = document.querySelectorAll( 'body *' );
    console.log(elements[0].innerHTML);
    console.log('ya');
  });
}

display();

The variable elements is supposed to get all of the elements inside of the body of the API that it just fetched, and then the console.log statement after that is supposed to log the innerHTML of the first element. 变量元素应该将所有元素都获取到它刚获取的API的内部,然后在那之后的console.log语句记录第一个元素的innerHTML。 However, it's not logging anything. 但是,它没有记录任何内容。

So there were a number of issues with the code: 因此,代码存在许多问题:
1. You are querying the document, but your data is held in the Data variable. 1.您正在查询文档,但是您的数据保存在Data变量中。 Trying logging out the Data variable. 尝试注销Data变量。
2. The GET was not formed correctly to allow for a Cross Browser request, when I tried it. 2.尝试时,GET格式不正确,无法允许跨浏览器请求。 The following code worked for me: 以下代码为我工作:

function display(){
        $.ajax({
            type: "GET",
            url: "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Stack%20Overflow&callback=?",
            contentType: "application/json; charset=utf-8",
            async: true,
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                console.log(data);
            },
            error: function (errorMessage) {
            }
        });
    }

    display();

Note: I had to add a callback parameter to the original search URL. 注意:我必须在原始搜索URL中添加一个回调参数。

I used the following blog as a reference: http://www.9bitstudios.com/2014/03/getting-data-from-the-wikipedia-api-using-jquery/ 我使用以下博客作为参考: http : //www.9bitstudios.com/2014/03/getting-data-from-the-wikipedia-api-using-jquery/

The query shown here returns a data object, not an HTML string. 此处显示的查询返回一个数据对象,而不是HTML字符串。 So, using query selectors would not be appropriate. 因此,使用查询选择器是不合适的。

You are not setting elements to the right thing, try: 您没有将元素设置为正确的东西,请尝试:

function display(){
    $.get('https://URL', function(data){
        var parser = new DOMParser()
        , doc = parser.parseFromString(data, "text/xml");
        console.log(doc);
        var elements = doc.querySelectorAll( 'body *' );
        console.log(elements[0].innerHTML);
    })
}

display()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM