Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
109
rated 0 times [  115] [ 6]  / answers: 1 / hits: 7896  / 4 Years ago, sat, may 16, 2020, 12:00:00

I got a mock server who responds with a body text like this: 2020-05-02 2020-05-05 2020-05-07 2020-05-15 2020-05-16 then I try to insert each o these elements in an javascript array using this func:



<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>


In browser console I see this error and my select element is not created in html page:



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)

More From » jquery

 Answers
2

This is the script that worked for me:



<script>
$(document).ready(function() {
fetch('http://127.0.0.1:35980/returnBalancesDates')
.then(dataWrappedByPromise => dataWrappedByPromise.text())
.then(data => {
console.log(data)
var choices = data.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>

[#3793] Thursday, May 14, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminkyrap

Total Points: 631
Total Questions: 89
Total Answers: 109

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
jazminkyrap questions
;