首页 > 解决方案 > AJAX 在客户端输入上运行 nodejs 文件

问题描述

我一直在摆弄nodejs和html,我想在客户端单击按钮时运行nodejs child_process。当然我不能直接在浏览器上运行的 html 中执行此操作,所以我认为我应该向服务器端发出 ajax 请求,以便它可以运行另一个文件(它将在终端中运行命令来执行 python 脚本)。

我有一个app.js读取文件并将其输出到浏览器

我还有一个index.html包含按钮和funcs.js以及我想在单击按钮后运行的脚本

我怎样才能提出那个ajax请求?

这是我的代码:

索引.html

<!DOCTYPE html>
<html lang="fr">
  <head>
    <meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <title>Lights</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

  </head>
  <body class="text-white bg-dark">
    <center>
    <input type="submit" value="OFF" name="OFF" onclick="turnOff()">
    <input type="submit" value="ON" name="ON" onclick="turnOn()">
    </center>
    
    <div id="texttest"> </div>
    <div id="fil"> </div>
    
    
    
    <script>
    
    function turnOff() {
        
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("texttest").innerHTML = "trying off";
            }
        };
        xhttp.open("GET", "funcOff.js", true);
        xhttp.send();

/*      $.ajax({
            type: 'POST',
            url: "funcOff.js",
            success: function(response){
                document.getElementById("texttest").innerHTML = "trying off";
            }
        });*/
        
        }
        
    function turnOn() {
    
        $.ajax({
            type: 'GET',
            url: "turnOn.py",
            success: function(response){
                document.getElementById("texttest").innerHTML = "trying on";
            }
        });
        
        }

    </script>
    
  </body>
</html>

应用程序.js

http = require("http"),
path = require("path"),
url = require("url"),
fs = require("fs");
const {exec} = require('child_process');

function sendError(errCode, errString, response)
{
  response.writeHead(errCode, {"Content-Type": "text/plain"});
  response.write(errString + "\n");
  response.end();
  return;
}

function sendFile(err, file, response)
{
  if(err) return sendError(500, err, response);
  response.writeHead(200);
  response.write(file, "binary");
  response.end();
}

function getFile(exists, response, localpath)
{
  if(!exists) return sendError(404, '404 Not Found', response);
  fs.readFile(localpath, "binary",
   function(err, file){ sendFile(err, file, response);});
}

function getFilename(request, response)
{
  var urlpath = url.parse(request.url).pathname; // following domain or IP and port
  var localpath = path.join(process.cwd(), urlpath); // if we are at root
  fs.exists(localpath, function(result) { getFile(result, response, localpath)});
}

var server = http.createServer(getFilename);
server.listen(1000);
console.log("Server available...");  

funcOn.js

const { exec } = require('child_process');


exec('python3 turnOn.py', (err, stdout, stderr) => {
  if (err) {
    //some err occurred
    console.error(err)
  } else {
   // the *entire* stdout and stderr (buffered)
   console.log(`stdout: ${stdout}`);
   console.log(`stderr: ${stderr}`);
  }
});

我先跑node app.js然后我去localhost:1000/index.html。在浏览器上,我可以单击按钮并有响应,但脚本没有运行

感谢您的帮助

标签: node.jsajax

解决方案


推荐阅读