简体   繁体   English

如何将来自 NodeJS API 的数据作为变量传递给 static JS 文件?

[英]How to pass data from NodeJS API as a variable to a static JS file?

I have made a NodeJS REST API, which returns JSON data of questions I have a static JS file which does DOM manipulations on client side to show different questions in an order, it takes questions from the questions array. I have made a NodeJS REST API, which returns JSON data of questions I have a static JS file which does DOM manipulations on client side to show different questions in an order, it takes questions from the questions array.

I am able to get data from the API on the pug render engine and to pass it on the main page, but unable to find a way to pass that data as a variable to the JS file which does DOM manipulation on the page.我能够从 pug 渲染引擎上的 API 获取数据并将其传递到主页上,但无法找到将这些数据作为变量传递给在页面上进行 DOM 操作的 JS 文件的方法。

I have thought of an approach to fetch data from API in the static js file itself but it doesn't seem to be an effective approach because request to API is done in the render engine itself.我想到了一种从 static js 文件本身中的 API 获取数据的方法,但这似乎不是一种有效的方法,因为对 API 的请求是在渲染引擎本身中完成的。

My viewsConroller:我的意见控制器:

视图控制器

My pug template is able to access the questions:我的哈巴狗模板能够访问问题:

哈巴狗模板和渲染页面

but I can't find a way to send questions array as a variable to the static JS file which does the DOM manipulation.但我找不到将问题数组作为变量发送到执行 DOM 操作的 static JS 文件的方法。

I think fetching the json data in your static js file would be the best thing.我认为在 static js 文件中获取 json 数据将是最好的选择。 Other than that you could do this:除此之外,您可以这样做:

let questions = document.querySelectorAll('.overview-box__text').map((el) => JSON.parse(el.innerText));

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

相关问题 从 static js 文件 nextJs 传递变量更新 - Pass variable update from static js File nextJs 在NodeJS中将数据从一个js文件同步传递到另一个 - Pass data from one js file to other synchronously in NodeJS 如何将js中的变量从服务器端传递到nodejs中的客户端 - How to pass variable in js from serverside to clientside in nodejs 如何在Nodejs中将变量从一个API传递到另一个 - How to pass variable from one API to another in Nodejs 如何将数据/变量从file_controller.rb传递到application.js - How can pass data/variable from file_controller.rb to application.js 如何将变量传递到.js文件 - how to pass variable into .js file 如何将变量从 js 文件传递到 .vue 文件 - How to pass a variable from js file to a .vue file React - 如何将 API 数据从一个组件传递到另一个 js 文件中的另一个组件? - React - How can I pass API data from one component to another in a different js file? 如何将 popup.js 文件中的单个字符串变量传递给 chrome 扩展 API 上的单独 javascript 文件? - How can I pass a single string variable from a popup.js file to a seperate javascript file on chrome extension API? 如何将变量从html表单传递到.js文件? - How to pass a variable from a html form to a .js file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM