我正在做一个作业,需要我从URL http://quotes.rest/qod?category=inspire中获取数据;具体来说,<quote>和<author>标记的内容。为此,我使用XMLHttpRequest;问题是,如果我设置xhr.responseType = 'document'(或使用xhr.responseXML),则尝试放入请求的变量变为null。如果使用xhr.responseText,则可以字符串形式正确表示站点,并且可以解决与此有关的问题,但这并不是我打算这样做的方式。我试图将字符串解析为XML文档,但是在xhr.responseText每个<>括号中得到的字符串都替换为",导致解析产生了错误的XML文档。请帮助我解决这两个问题之一,或者以正确的XML语法获取XML文档或字符串,非常感谢。var doc;var x; function submit() { var xhr = new XMLHttpRequest(); // here adding xhr.responseType = 'document' doesn' t change the outcome xhr.onreadystatechange = function () { if (xhr.readyState === 4) { doc = xhr.responseXML; } } xhr.open('get', 'http://quotes.rest/qod?category=inspire', true); xhr.send();}function trial(){ x = doc.getElementsByTagName("quote")[0].childNodes[0].nodeValue; //by this point doc is null, so I get an error here console.log( x );}<h5>Press to see the quote of the day:</h5><input type="submit" value="Start" onclick="submit()"><!-- the first button fetches the data from the URL --><input type="submit" value="Trial" onclick="trial()"><!-- the second one is supposed to show on console the quote -->
添加回答
举报
0/150
提交
取消