2015-04-03 103 views
1

我想要做什麼:用戶單擊網頁上的按鈕時,它會執行一個node.js腳本,該腳本在node.js頁面上執行服務器端操作。從頁面運行Node.JS javascript按鈕

示例:每次有人點擊頁面上的按鈕時,Node.js都會在服務器控制檯上輸出消息。

目前爲止我可以做些什麼:我可以用node.js + express展示一個頁面。我無法讓服務器端的操作發生。

 <button type="button" onclick="testF()">Click</button> 
     <script> 
     function testF(){ 
      alert('Hello world!'); 
      console.log('clicked!!'); //Id like this to show on the node.js console 
     } 
     </script> 

謝謝!

+0

你需要AJAX或頁面重載爲 – adeneo 2015-04-03 14:08:17

+0

你需要使用'AJAX '這種事情。如果你對圖書館沒有意見,[jQuery](http://api.jquery.com/jquery.ajax/)是事實上的選擇。然後,您需要使用express來公開端點以接受http請求。 – 2015-04-03 14:08:46

回答

6

你不需要使用快遞。 Node.js非常簡單。

根據其他成員,您必須使用AJAX,所以... jQuery也不是必需的。

看看我爲你製作的下面的代碼(只記得我做了一個非常弱的代碼,因爲如果我寫一個更安全的代碼可能會比你期望的大)。

的test.html

<button type="button" onclick="testF()">Click</button> 
<script> 
    function testF() 
    { 
    alert('Hello world!'); 

    var xmlhttp = new XMLHttpRequest(); 
    xmlhttp.open("get", "/service"); 

    xmlhttp.onreadystatechange = function() 
    { 
     // DONE 
     if (xmlhttp.readyState == 4) 
     { 
     switch(xmlhttp.status) 
     { 
      case 200: 
      alert("OK"); 
      break; 
      case 404: 
      alert("Not Found"); 
      break; 
      case 500: 
      alert("Internal Server Error"); 
      break; 
      default: 
      alert("Unexpected Error. HTTP Status: " + xmlhttp.status); 
     } 
     } 
    }; 

    xmlhttp.send(); 
    } 
</script> 

server.js(Node.js的)

var nsHttp = require("http"); 
var nsUrl = require("url"); 
var nsPath = require("path"); 
var nsFs = require("fs"); 

var srv = nsHttp.createServer(function(req, res) 
{ 
    var pathname = nsUrl.parse(req.url).pathname; 

    // check URL to send the right response 
    switch(pathname) 
    { 
    case "/favicon.ico": 
     res.end(); 
     break; 

    case "/": 
     HTTP_SendHtmlFile(res, nsPath.join(__dirname, "test.html")); 
     break; 

    case "/service": 
     console.log("clicked!"); 
     HTTP_SendOK(res, ""); 
     break; 

    default: 
     HTTP_SendNotFound(res); 
    } 
}); 

// reads a file contents and sends, but if any error occur, 
// sends a 500 HTTP Status Code (Internal Server Error) 
function HTTP_SendHtmlFile(res, filepath) 
{ 
    nsFs.readFile(filepath, function(err, data) { 
    if (err) { 
     HTTP_SendInternalServerError(res); 
     return; 
    } 

    HTTP_SendOK(res, data); 
    }); 
} 

function HTTP_SendOK(res, body) 
{ 
    res.writeHead(200, {"Content-type": "text/html"}); 
    res.end(body); 
} 

function HTTP_SendInternalServerError(res) 
{ 
    res.writeHead(500, {"Content-type": "text/html"}); 
    res.end(); 
} 

function HTTP_SendNotFound(res) 
{ 
    res.writeHead(404, {"Content-type": "text/html"}); 
    res.end(); 
} 

srv.listen(8080); 
+0

謝謝!我也一直在嘗試socket.io,它似乎也在爲我製造詭計。 – user3765743 2015-04-03 15:33:42