[英]how to call function on the basis of particular button in node.js express
我想根據單擊哪個按鈕來調用函數。
我這里有EJS文件,稱為test.ejs
<form>
<input type="submit" value="Click here 1"></input>
<input type="submit" value="Click here 2"></input>
<input type="submit" value="Click here 3"></input>
<input type="submit" value="Click here 4"></input>
</form>
而且我有JS文件名test.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
console.log("Get the Request from test...!!!");
});
function button1(){
console.log("User Click Button 1");
}
function button2(){
console.log("User Click Button 2");
}
function button3(){
console.log("User Click Button 3");
}
function button4(){
console.log("User Click Button 4");
}
module.exports = router;
當按鈕1與按鈕2,3和4類似地單擊時,我想調用fuction button1()
。
程序是什么。 請幫我舉個例子。
您可以使用AJAX或WebSockets:
AJAX:
(我假設您有jQuery)
HTML:
<button id='button1'> Test </button>
JS(客戶端):
$('#button1').click(function(){
console.log('button clicked');
$.ajax({url: 'test1', success:function(res){
console.log('server response is', res);
}});
});
JS(服務器):
function buttonAction1(res){
res.send('ok');
}
router.get("/test1", function (req, res) {
buttonAction1(res);
});
WebSockets簡介:
我更喜歡使用socket.io之類的東西。 這是您可以使用的一些教程 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.