如何解析这个api中的数据并将其显示在我的html中?

时间:2017-07-22 23:53:08

标签: javascript html json api

我是javascript的新手,并且花了过去几个小时尝试在我的html文档中将api url中的json数据解析到我的身体中。我对API的唯一体验是使用C#包装器,所以这对我来说是新的。

这是API网址:https://catfact.ninja/fact

我不知道从哪里开始。我已经能够成功地提取我想要的数据,但我只能将它打印到控制台,我不知道如何将数据拉入html。这是我的javascript代码:

var HttpClient = function() {
this.get = function(aUrl, aCallback) {
    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
    var anHttpRequest = new XMLHttpRequest();
    anHttpRequest.onreadystatechange = function() {
        if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
            aCallback(anHttpRequest.responseText);
    }

    anHttpRequest.open( "GET", aUrl, true );
    anHttpRequest.send( null );
    }
}
var client = new HttpClient();
client.get('https://catfact.ninja/fact', function(response) {
    var vsplit = response.split("\"")
    console.log(vsplit[3]);
    $('body').html(document.write(vsplit[3]));

});

感谢您的帮助,抱歉,如果我显得愚蠢

1 个答案:

答案 0 :(得分:0)

你遇到的第一个问题是在html函数中调用document.write不会产生你想到的结果。 document.write是一个同步写入函数,它尝试在调用它的位置将一个字符串注入DOM渲染器。如果你删除它,你应该有更多的运气看到HTML中的东西,但你也可以使用以下。

https://catfact.ninja/fact的回复如下。

{"fact":"Cats' eyes shine in the dark because of the tapetum, a reflective layer in the eye, which acts like a mirror.","length":109}

当格​​式为JSON时,无需拆分响应。您可以使用JSON.parse创建Javascript对象。例如。

// data will contain data.fact, and data.length 
var data = JSON.parse(response);

// Without using jQuery, you can set the html of the body directly
var body = document.getElementsByTagName("body")[0];
body.innerHTML = data.fact;
相关问题