【问题标题】:load external .js file from HTML从 HTML 加载外部 .js 文件
【发布时间】:2018-03-16 21:09:40
【问题描述】:

我有一个简单的 HTML 文件,我想从中加载 .js 文件。 我有这些文件(文件在同一个文件夹中):

start.js

var http = require('http');
var fs = require('fs');

http.createServer(function (req, response) {
    fs.readFile('index.html', 'utf-8', function (err, data) {
        response.writeHead(200, { 'Content-Type': 'text/html' });
        response.write(data);
        response.end();
    });
}).listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
       <script src="http://mrdoob.github.com/three.js/build/three.min.js"></script>
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type= "text/javascript" src="./SetData.js"></script>
        <title>main project demo</title>
    </head>
    <body>
    </body>
</html>

和 SetData.js

console.log("Its me");

我正在使用 node.js,所以我以 node start.js 开始我的项目 在 index.html 我想用

调用本地 SetData.js 文件
<script type= "text/javascript" src="./SetData.js"></script>

但是网页上没有显示,只有这个错误

我已经尝试从另一个文件夹调用 .js 文件或从正文部分调用它。总是同样的错误。 如何从 HTML 加载本地 .js 文件?

【问题讨论】:

标签: javascript html node.js


【解决方案1】:

你可以使用这样的东西

<script src="myscripts.js"></script>

【讨论】:

    【解决方案2】:

    将 start.js 中的代码替换为以下代码。已经回答了here

    var fs = require("fs");
    var http = require("http");
    var url = require("url");
    
    http.createServer(function (request, response) {
    
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");
    
    response.writeHead(200);
    
        if(pathname == "/") {
            html = fs.readFileSync("index.html", "utf8");
            response.write(html);
        } else if (pathname == "/SetData.js") {
            script = fs.readFileSync("SetData.js", "utf8");
            response.write(script);
        }
        response.end();
    }).listen(1337, '127.0.0.1');
    
    console.log('Server running at http://127.0.0.1:1337/');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-29
      • 2016-06-25
      • 1970-01-01
      • 2016-09-03
      • 2019-02-11
      • 2013-12-13
      • 2010-09-11
      相关资源
      最近更新 更多