【问题标题】:How do I get the JSON data to return? [duplicate]如何让 JSON 数据返回? [复制]
【发布时间】:2021-04-03 14:06:56
【问题描述】:

我想从另一个表中获取数据以在详细视图中使用。但是从 getData 方法返回的值是 null。我该怎么办?

<th data-field="id" data-detail-formatter="DetailFormatter">ID</th>
<th data-field="prefix" data-detail-formatter="DetailFormatter">Prefix</th>
<th data-field="fname" data-detail-formatter="DetailFormatter"Name</th>

function DetailFormatter(index, row) {
   return '<p> ID: ' + row.id + '</p>',
          '<p> Name: ' + row.prefix + '</p>',
          '<p> Price: ' + row.fname + '</p>',
          '<p> Degree: ' + getData() + '</p>'
}

function getData() {
   var data

   $.getScript('http://localhost:55289/ManageTeacher/GetTacherDegree', function (script, status, jqxhr) {
      data = script
   });

   return data
}

【问题讨论】:

    标签: javascript html jquery bootstrap-4 bootstrap-table


    【解决方案1】:

    这是一种异步过程。您可以在回调函数中获得正确的值。所以你可以在回调函数中移动处理data的代码,而不是返回data

    function getData() {
       var data
    
       $.getScript('http://localhost:55289/ManageTeacher/GetTacherDegree', function (script, status, jqxhr) {
          data = script.  // <--------------- right place
       });
    
       return data // <------------------- wrong place
    }
    

    【讨论】:

    • 我不明白,对不起:(
    • 您必须在回调中编写代码。在它之外,您无法获得正确的数据。在它之外,它总是未定义的。
    【解决方案2】:

    尝试在异步函数中使用 fetch api

    async function getData() {
    
    const data = await fetch('http://localhost:55289/ManageTeacher/GetTacherDegree')
    .then(res => res.json())
    
     return data
     }
    

    【讨论】:

    • 如何获得对象承诺值?
    猜你喜欢
    • 1970-01-01
    • 2020-02-07
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    相关资源
    最近更新 更多