使用fetch JavaScript API,您可以尝试:
response.text().then(function (text) {
// do something with the text response
});
ES6 语法:
fetch("URL")
.then(response => response.text())
.then((response) => {
console.log(response)
})
.catch(err => console.log(err))
你可以用两种不同的方式实现这个功能:
The first option is to use the response.text()
method, but be aware that, at Dec/2019, its global usage is only 36.71%:
async function fetchTest() {
let response = await fetch('https://httpbin.org/encoding/utf8');
let responseText = await response.text();
document.getElementById('result').innerHTML = responseText;
}
(async() => {
await fetchTest();
})();
<div id="result"></div>
The second option is to use the response.body
property instead, which requires a little more work but has 73.94% of global usage:
async function fetchTest() {
let response = await fetch('https://httpbin.org/encoding/utf8');
let responseText = await getTextFromStream(response.body);
document.getElementById('result').innerHTML = responseText;
}
async function getTextFromStream(readableStream) {
let reader = readableStream.getReader();
let utf8Decoder = new TextDecoder();
let nextChunk;
let resultStr = '';
while (!(nextChunk = await reader.read()).done) {
let partialData = nextChunk.value;
resultStr += utf8Decoder.decode(partialData);
}
return resultStr;
}
(async() => {
await fetchTest();
})();
<div id="result"></div>
response.text()
的成功率为93.14%。 - Paul Rooney
typeof
来检查返回的类型,如果是对象,则执行某些操作,如果是字符串,则执行其他操作。 - Mohd Asim Suhail