GET请求返回数据正常,赋值reportId变量时出现undefined问题求助
问题原因及解决方法
问题根源
后端返回的是包含多个ReportsModel对象的数组,但前端代码直接尝试访问数组本身的URL属性——数组并没有这个属性,因此reportId会返回undefined。
修复代码
修改JavaScript中获取reportId的逻辑,改为取数组第一个元素的URL属性:
function showReport(reportName) { const iframe = document.getElementById('iframe_a'); $.ajax({ url: "/ReportsApi/generateReport/" + reportName, type: "GET", contentType: "application/json; charset=utf-8", success: function (data) { console.log(data); if (data && data.length > 0) { // 取数组第一个元素的URL属性 const reportId = data[0].URL; console.log(reportId); iframe.src = `${reportId}&autoAuth=true&pageNavigation=true`; } else { console.error('Error: No data returned from server'); } }, error: function (error) { console.error('Error updating data:', error); } }); }
补充说明
后端控制器通过foreach循环将每行数据转为ReportsModel实例并加入列表,最终返回的是数组格式的响应。前端需要对应访问数组中的具体元素,才能拿到目标URL值。
内容的提问来源于stack exchange,提问作者Arjun-S96
相关产品推荐
相关产品推荐

