简体   繁体   English

使用 JSON 动态创建 function 的内容正在将未定义返回到外部 function 调用 ZDE9B9ED78D7E2EZEZ1

[英]A dynamically content creating function using JSON is returning undefined to an outside function call in javascript

I wanted to make a TO-DO list app for an assignment using https://jsonplaceholder.typicode.com/todos .我想为使用https://jsonplaceholder.typicode.com/todos的作业制作一个 TO-DO 列表应用程序。 The code snippet is shown below.代码片段如下所示。

 function generateList() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var response = JSON.parse(this.responseText); var output = ""; for (let i = 0; i < response.length; i++) { // console.log(response[i].title); if (response[i].completed == true) { output += `<tr id='row${response[i].id}'>`; output += `<td><input type="checkbox" id="task${response[i].id}" checked disabled></td>`; output += `<td>${response[i].title}</td>`; } else { output += `<tr id='row${response[i].id}'>`; output += `<td><input type="checkbox" id="task${response[i].id}"></td>`; output += `<td>${response[i].title}</td>`; } output += "</tr>"; } // document.querySelector("tbody").innerHTML = output; return output; } }; xhttp.open("GET", "https://jsonplaceholder.typicode.com/todos", true); xhttp.send(); } let temp = generateList(); document.querySelector("tbody").innerHTML = temp;
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Success</h1> <table> <tbody> </tbody> </table> <script src="./json.js"></script> </body> </html>

The problem I am facing is that, the table is not displaying.我面临的问题是,表格没有显示。 Instead it is showing undefined .相反,它显示undefined When I used the innerHTML method inside the function instead of return statement (I have commented that statement above the return statement), it worked perfectly as I wanted.当我在 function 中使用 innerHTML 方法而不是 return 语句时(我已在 return 语句上方评论了该语句),它可以完美地按照我的意愿工作。 Can anyone tell me, why am I facing this error?谁能告诉我,为什么我会遇到这个错误?

That's because xhttp.onreadystatechange executes asynchronously and generateList() immediately returns undefined for this call:这是因为xhttp.onreadystatechange异步执行,并且generateList()立即为此调用返回undefined

let temp = generateList(); //this just returns undefined
document.querySelector("tbody").innerHTML = temp;

In the above call temp will be undefined since the function ( generateList ) didn't return anything ( falsy ).在上面的调用中temp将是undefined的,因为 function ( generateList ) 没有返回任何东西 ( falsy )。 And then xhttp.onreadystatechange goes ahead with its usual asynchronous call, fetches that data and manipulates the output .然后xhttp.onreadystatechange继续其通常的异步调用,获取该数据并操作output So you can call another function after it's done with manipulating the output因此,在完成对 output 的操作,您可以调用另一个output

Note that due to the above reason your return output;请注意,由于上述原因,您return output; doesn't actually do anything.实际上并没有做任何事情。

So, this is what you can do:所以,这就是你可以做的:

xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var response = JSON.parse(this.responseText);
      var output = "";
      for (let i = 0; i < response.length; i++) {
        ....
        ....
        output += '...'
      }
      callFunction(output) //invoke a function with this output
      // document.querySelector("tbody").innerHTML = output;
      return output; //NOT needed
    }

Now you can get the output in this现在您可以在此获得 output

callFunction(output){
  //here you can do anything with the output. for e.g
  document.querySelector("tbody").innerHTML = output;

}

You can also go ahead with publisher and subscriber architecture where after the response is received, an event will be dispatched along with output and there will be a subscriber 'listening' to it which will consume this output.您还可以在publisher者和subscriber架构之前使用 go,其中在收到响应后,将与output一起调度一个事件,并且将有一个订阅者“监听”它,它将使用这个 Z78E6221F6393D1356DZ681DB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM