当我尝试将作为文本接收的正文分配给 javascript 中的变量时,为什么会出现 Uncaught TypeError: response.text is not a function" 错误

And*_*rei 2 javascript jquery select http drop-down-menu

我有一个模拟服务器,它的正文文本如下所示:“2020-05-02 2020-05-05 2020-05-07 2020-05-15 2020-05-16”然后我尝试插入这些元素在 JavaScript 数组中使用此函数:

<script>
    $(document).ready(function() {
        let response = fetch("http://127.0.0.1:35980/returnBalancesDates")
        let value =  response.text();
        var choices =  value.split(' ');
        console.log(choices)
        var x = document.createElement("SELECT");
        x.setAttribute("id", "mySelect");
        x.setAttribute("name", "oldbaldate");
        document.body.appendChild(x);

        for (i = 0; i < choices.length; i = i + 1) {
            var z = document.createElement("option");
            z.setAttribute("value", choices[i]);
            var t = document.createTextNode(choices[i]);
            z.appendChild(t);
            document.getElementById("mySelect").appendChild(z);
        }
        $(x).appendTo('#selectOldBalance');
    });
</script>
Run Code Online (Sandbox Code Playgroud)

在浏览器控制台中,我看到此错误,并且我的选择元素未在 html 页面中创建:

Uncaught TypeError: response.text is not a function
    at HTMLDocument.<anonymous> ((index):75)
    at e (jquery.min.js:2)
    at t (jquery.min.js:2)
Run Code Online (Sandbox Code Playgroud)

小智 7

Fetch 是异步的,因此当您调用时response.text()实际上还没有响应。要么使用response = await fetch,要么回调。