如何将OpenAI API返回的JS格式响应添加到HTML的script标签中?
自动将OpenAI API的JS响应写入HTML script标签的方法
方法1:用Node.js脚本直接生成HTML文件
- 先安装OpenAI的官方包:
npm install openai - 写一个简单的脚本,调用API拿到响应后,自动把JS内容塞进HTML的script标签并生成文件:
const { OpenAI } = require('openai'); const fs = require('fs'); // 替换成你的OpenAI API密钥 const openai = new OpenAI({ apiKey: 'your-api-key-here' }); async function generateHTML() { // 调用API获取过滤后的JS内容 const completion = await openai.chat.completions.create({ model: "gpt-3.5-turbo", messages: [{ role: "user", content: "生成一段过滤后的JS代码,比如简单的日期格式化函数" }], }); // 提取响应里的纯JS内容 const jsCode = completion.choices[0].message.content.trim(); // 构造完整的HTML结构 const htmlContent = ` <!DOCTYPE html> <html> <head> <title>自动生成页面</title> </head> <body> <script> ${jsCode} </script> </body> </html> `; // 写入HTML文件 fs.writeFileSync('auto-generated.html', htmlContent); console.log('HTML文件已生成,JS内容已自动插入script标签!'); } // 执行脚本 generateHTML();
- 运行脚本:
node generate.js,就能得到自动插入了目标JS的HTML文件。
方法2:浏览器端直接调用并动态插入(适合前端新手)
- 直接在HTML里写JS逻辑,调用API后动态创建script标签并插入内容:
<!DOCTYPE html> <html> <body> <button onclick="fetchAndInsertJS()">点击获取并插入JS</button> <script> async function fetchAndInsertJS() { try { const res = await fetch('https://api.openai.com/v1/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your-api-key-here' }, body: JSON.stringify({ model: "gpt-3.5-turbo", messages: [{ role: "user", content: "生成过滤后的JS代码,比如一个按钮点击提示的函数" }] }) }); const data = await res.json(); const jsCode = data.choices[0].message.content.trim(); // 创建script标签并插入到页面 const scriptTag = document.createElement('script'); scriptTag.textContent = jsCode; document.body.appendChild(scriptTag); alert('JS内容已自动插入页面!'); } catch (err) { console.error('出错了:', err); } } </script> </body> </html>
- 注意:浏览器直接调用API会有跨域问题,新手可以用本地服务器打开(比如执行
npx serve),或者用后端做请求中转。
关键提醒
- 绝对不要把API密钥直接写在前端公开代码里,上线项目一定要通过后端中转请求,防止密钥泄露。
- 调用API时,提示词要明确要求返回纯JS代码,不要带多余的解释性文字,避免插入后出现语法错误。
内容的提问来源于stack exchange,提问作者Monke
相关产品推荐
相关产品推荐

