如何在Node.JS中将函数从HTML调用到Javascript文件

时间:2023-01-09 18:59:05

I am using Node.JS with Express. The following line fails, and I need help fixing it.

我正在使用Node.JS和Express。以下行失败了,我需要帮助修复它。

var routines = require("myJsRoutines.js");

When I run index.html and click MenuItem, I get the first alert, but not the second one. I have both files in the same directory. Thanks

当我运行index.html并单击MenuItem时,我得到第一个警报,但不是第二个警报。我有两个文件在同一目录中。谢谢

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <a href="javascript:myMenuFunc('Level 1');">MenuItem</a>
    <script>function myMenuFunc(level) {
        alert("myMenuFunc1:" + level);
        var routines = require("myJsRoutines.js");
        alert("myMenuFunc:2" + level);
        routines.processClick(level);
        alert("myMenuFunc:3" + level);
    }</script>
</body>
</html>

myJsRoutines.js:

exports.processClick = function processClick (param1) {
    console.log(param1)
}

3 个解决方案

#1


0  

Script in <script> tags only runs on the client, and script on the server never directly handles DOM events like clicks. There is no magical event wireup - you need to make them interact.

Assuming folder structure from http://expressjs.com/en/starter/generator.html

假设来自http://expressjs.com/en/starter/generator.html的文件夹结构

Updated module code, in /modules/myJsRoutines.js...

更新了模块代码,在/modules/myJsRoutines.js中...

var myJsRoutines = (function () {
  var multiplier = 2;

  return {
    processLevel: function (level, callback) {
      console.log('processLevel:', level); // CLI or /logs/express_output.log

      // validation
      if (!level) {
        // error is usually first param in node callback; null for success
        callback('level is missing or 0');
        return; // bail out
      }

      // processing
      var result = level * multiplier;

      // could return result, but need callback if code reads from file/db
      callback(null, result);
    }
  };
}()); // function executed so myJsRoutines is an object

module.exports = myJsRoutines;

In /app.js, load your module and add a get method...

在/app.js中,加载模块并添加get方法......

var myJsRoutines = require('./modules/myJsRoutines');

app.get('/test', function (req, res) {
  var level = parseInt(req.query.level) || 0;
  console.log('server level:', level);

  myJsRoutines.processLevel(level, function (err, result) {
    if (err) {
      res.status(500);
      return res.send(err);
    }

    res.send('result ' + (result || '') + ' from the server');
  });
});

In /public/index.html, add client script to make an HTTP request to the get method...

在/public/index.html中,添加客户端脚本以向get方法发出HTTP请求...

<a class="test" href="#" data-level="1">Test Level 1</a>
<a class="test" href="#" data-level="2">Test Level 2</a>

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$(function(){ // jQuery DOM ready
  $('.test').click(function () { // click event for <a class="test">
    var level = $(this).data('level'); // from data-level="N"
    var url = '/test?level=' + escape(level);
    console.log('client url:', url);

    // HTTP GET http://localhost:3000/test?level=
    $.get(url, function (data) {
      console.log('client data:', data); // browser console
    });

    return false; // don't navigate to href="#"
  });
});
</script>

...start the server from the command line...

...从命令行启动服务器...

npm start

...open http://localhost:3000/ in your browser, Ctrl+Shift+i to open the browser console, and click the links.

...在浏览器中打开http:// localhost:3000 /,按Ctrl + Shift + i打开浏览器控制台,然后单击链接。

#2


0  

Run from a node server..var routines = require("myJsRoutines.js"); in the server.js file and Just call a javascript onclick function..and post parameters..for posting parameters..you'll be needing Ajax...and console log the data in node..or After sending the data to the node server..run the function in node server.

从节点server..var例程= require(“myJsRoutines.js”)运行;在server.js文件中,只需调用一个javascript onclick函数..并发布参数...用于发布参数..你将需要Ajax ...并且控制台在node..or中记录数据后将数据发送到node server..run节点服务器中的函数。

Code snippet for calling the function from a href.. and

用于从href调用函数的代码片段

`<a href="www.blabla.com" onclick="return myMenuFunc('Level 1');">MenuItem</a>

<script type="text/javascript">
function myMenuFunc('Level 1') {
    // return true or false, depending on whether you want to allow the `href` property to follow through or not
}

`

#3


0  

This line:

var routines = require("myJsRoutines.js");

fails because the require statement is a nodejs function. It does not work with the browser nor does it work with javscript natively. It is defined in nodejs to load modules. To see this

失败,因为require语句是nodejs函数。它不适用于浏览器,也不适用于javscript本机。它在nodejs中定义为加载模块。看到这个

go to your command line and run this

转到命令行并运行它

> node
> typeof require
'function'

go to your browser console; firefox - press Ctrl + K

转到浏览器控制台; firefox - 按Ctrl + K.

>> typeof require
"undefined"

To achieve your aim, there are two options that come to my mind

为了实现您的目标,我想到了两种选择

// Assumed Express server running on localhost:80
var express = require('express');
var app = express();

app.get("/myJsRoutines", loadRoutines);

app.listen(80);

Option I: XMLHttpRequest This is a browser API that allows you to open a connection to a server and talk with the server to collect stuff using HTTP. Here's how you do this

选项I:XMLHttpRequest这是一个浏览器API,允许您打开与服务器的连接并与服务器通信以使用HTTP收集内容。这是你如何做到这一点

<script>
    var request = new XMLHttpRequest(); // create an xmlhttp object
    request.open("GET", "/myJsRoutines"); // means GET stuff in there
    request.link = link;

    // wait for the response
    request.addEventListener("readystatechange", function() {
       // checks if we are ready to read response
       if(this.readyState === 4 && this.status === 200) {
            // do something with response
        }

    })       

    //send request
    request.send(); 
</script>

Lookup XMLHttpRequest API or the new fetch API

查找XMLHttpRequest API或新的fetch API

Option II: Pug Pug, formerly named jade is a templating engine for nodejs. How does it work? You use it to programmatically create the html on the server before sending it. Lookup the site -> https://pugjs.org/

选项二:Pug Pug,以前称为jade是nodejs的模板引擎。它是如何工作的?您可以在发送之前使用它以编程方式在服务器上创建html。查找网站 - > https://pugjs.org/

#1


0  

Script in <script> tags only runs on the client, and script on the server never directly handles DOM events like clicks. There is no magical event wireup - you need to make them interact.

Assuming folder structure from http://expressjs.com/en/starter/generator.html

假设来自http://expressjs.com/en/starter/generator.html的文件夹结构

Updated module code, in /modules/myJsRoutines.js...

更新了模块代码,在/modules/myJsRoutines.js中...

var myJsRoutines = (function () {
  var multiplier = 2;

  return {
    processLevel: function (level, callback) {
      console.log('processLevel:', level); // CLI or /logs/express_output.log

      // validation
      if (!level) {
        // error is usually first param in node callback; null for success
        callback('level is missing or 0');
        return; // bail out
      }

      // processing
      var result = level * multiplier;

      // could return result, but need callback if code reads from file/db
      callback(null, result);
    }
  };
}()); // function executed so myJsRoutines is an object

module.exports = myJsRoutines;

In /app.js, load your module and add a get method...

在/app.js中,加载模块并添加get方法......

var myJsRoutines = require('./modules/myJsRoutines');

app.get('/test', function (req, res) {
  var level = parseInt(req.query.level) || 0;
  console.log('server level:', level);

  myJsRoutines.processLevel(level, function (err, result) {
    if (err) {
      res.status(500);
      return res.send(err);
    }

    res.send('result ' + (result || '') + ' from the server');
  });
});

In /public/index.html, add client script to make an HTTP request to the get method...

在/public/index.html中,添加客户端脚本以向get方法发出HTTP请求...

<a class="test" href="#" data-level="1">Test Level 1</a>
<a class="test" href="#" data-level="2">Test Level 2</a>

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$(function(){ // jQuery DOM ready
  $('.test').click(function () { // click event for <a class="test">
    var level = $(this).data('level'); // from data-level="N"
    var url = '/test?level=' + escape(level);
    console.log('client url:', url);

    // HTTP GET http://localhost:3000/test?level=
    $.get(url, function (data) {
      console.log('client data:', data); // browser console
    });

    return false; // don't navigate to href="#"
  });
});
</script>

...start the server from the command line...

...从命令行启动服务器...

npm start

...open http://localhost:3000/ in your browser, Ctrl+Shift+i to open the browser console, and click the links.

...在浏览器中打开http:// localhost:3000 /,按Ctrl + Shift + i打开浏览器控制台,然后单击链接。

#2


0  

Run from a node server..var routines = require("myJsRoutines.js"); in the server.js file and Just call a javascript onclick function..and post parameters..for posting parameters..you'll be needing Ajax...and console log the data in node..or After sending the data to the node server..run the function in node server.

从节点server..var例程= require(“myJsRoutines.js”)运行;在server.js文件中,只需调用一个javascript onclick函数..并发布参数...用于发布参数..你将需要Ajax ...并且控制台在node..or中记录数据后将数据发送到node server..run节点服务器中的函数。

Code snippet for calling the function from a href.. and

用于从href调用函数的代码片段

`<a href="www.blabla.com" onclick="return myMenuFunc('Level 1');">MenuItem</a>

<script type="text/javascript">
function myMenuFunc('Level 1') {
    // return true or false, depending on whether you want to allow the `href` property to follow through or not
}

`

#3


0  

This line:

var routines = require("myJsRoutines.js");

fails because the require statement is a nodejs function. It does not work with the browser nor does it work with javscript natively. It is defined in nodejs to load modules. To see this

失败,因为require语句是nodejs函数。它不适用于浏览器,也不适用于javscript本机。它在nodejs中定义为加载模块。看到这个

go to your command line and run this

转到命令行并运行它

> node
> typeof require
'function'

go to your browser console; firefox - press Ctrl + K

转到浏览器控制台; firefox - 按Ctrl + K.

>> typeof require
"undefined"

To achieve your aim, there are two options that come to my mind

为了实现您的目标,我想到了两种选择

// Assumed Express server running on localhost:80
var express = require('express');
var app = express();

app.get("/myJsRoutines", loadRoutines);

app.listen(80);

Option I: XMLHttpRequest This is a browser API that allows you to open a connection to a server and talk with the server to collect stuff using HTTP. Here's how you do this

选项I:XMLHttpRequest这是一个浏览器API,允许您打开与服务器的连接并与服务器通信以使用HTTP收集内容。这是你如何做到这一点

<script>
    var request = new XMLHttpRequest(); // create an xmlhttp object
    request.open("GET", "/myJsRoutines"); // means GET stuff in there
    request.link = link;

    // wait for the response
    request.addEventListener("readystatechange", function() {
       // checks if we are ready to read response
       if(this.readyState === 4 && this.status === 200) {
            // do something with response
        }

    })       

    //send request
    request.send(); 
</script>

Lookup XMLHttpRequest API or the new fetch API

查找XMLHttpRequest API或新的fetch API

Option II: Pug Pug, formerly named jade is a templating engine for nodejs. How does it work? You use it to programmatically create the html on the server before sending it. Lookup the site -> https://pugjs.org/

选项二:Pug Pug,以前称为jade是nodejs的模板引擎。它是如何工作的?您可以在发送之前使用它以编程方式在服务器上创建html。查找网站 - > https://pugjs.org/