简体   繁体   English

如何通过 HTTP 获取 .js 文件并提取“导出”变量?

[英]How do I HTTP GET a .js file and extract 'exports' variables?

I am writing a site in Laravel to complement a game written in Node.我正在用 Laravel 编写一个站点来补充用 Node.js 编写的游戏。 It pulls information directly from the game's .js files stored on GitHub and the plan is to use Vue to generate some nice HTML to display the data.它直接从存储在 GitHub 上的游戏 .js 文件中提取信息,并计划使用 Vue 生成一些漂亮的 HTML 来显示数据。

The .js files are of the form: .js 文件的格式如下:

'use strict'

let x = {...};

exports.x = x;

I can import the files using a PHP request (simply using 'file') and pass them to JS with either jQuery.getScript or axios.get (so far).我可以使用 PHP 请求(仅使用“文件”)导入文件,并使用 jQuery.getScript 或 axios.get(到目前为止)将它们传递给 JS。 However, I am having real trouble coming up with a way to extract the 'x' values here under exports.但是,我真的很难想出一种方法来提取导出下的“x”值。 If I were writing a JS app in node, I would simply do the following:如果我在 node 中编写一个 JS 应用程序,我会简单地执行以下操作:

var xFile = require('xFile');

var x = xFile.x;

However, I can't figure out how to do that here as both GET methods return a string, not a JS file.但是,我无法弄清楚如何在此处执行此操作,因为这两个 GET 方法都返回一个字符串,而不是一个 JS 文件。 JSON.parse() doesn't work, and I would like to come up with a solution that doesn't just replace the non-JSON text as I would need a reusable solution for other files. JSON.parse() 不起作用,我想提出一个不仅替换非 JSON 文本的解决方案,因为我需要其他文件的可重用解决方案。 I don't suppose anybody has any ideas?我想没有人有任何想法吗?

Thanks so much!非常感谢!

You could try something like below.您可以尝试以下操作。

you could create the script tag dynamically and attach the script in the body and add your javascript code using innerHTML .您可以动态创建脚本标记并将脚本附加到正文中并使用innerHTML添加您的 javascript 代码。

You call this script in your ajax response code.您在 ajax 响应代码中调用此脚本。

 let script = document.createElement('script'); script.innerHTML = 'alert("Hi")'; document.querySelector('body').appendChild(script);

I managed to figure it out!我设法弄清楚了! It's a little janky, but you can run a node file in PHP with the exec command.它有点笨拙,但您可以使用exec命令在 PHP 中运行节点文件。 I just wrote a node file to import the file and return the useful data.我只是写了一个节点文件来导入文件并返回有用的数据。 This probably isn't an optimal solution, but it works for me since I'm much more confident with JS than with PHP.这可能不是最佳解决方案,但它对我有用,因为我对 JS 比对 PHP 更有信心。

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

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