从Javascript调用python时的问题

时间:2017-11-17 06:40:08

标签: javascript python html

我是Javascript,python和php的新手。我有一个js程序,其中我单击一个按钮,它调用python程序并接收返回值以显示在屏幕上。我试图避免使用Jquery和Json。

下面是Javascript和Python的代码。

使用Javascript:

<html>
<head>
<script>
function cal()
{
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function()
  {
     if (this.readyState == 4 && this.status == 200) {
     document.getElementById("do").innerHTML = this.responseText;
     }
  };
  xhttp.open("POST", "./pth.py", true);
  xhttp.send();

}
</script>
</head>
<body>
<input type="submit" id="submit" class="btn btn-default" name="Submit" 
onClick="cal();" value="Test"/>
<div id="do">

</div>
</body>
</html>

的Python:

#!/usr/bin/python

print "hello";

对于上面的代码,以下是我收到的输出(我看到整个python代码而不仅仅是hello)

#!/usr/bin/python print "hello";

1 个答案:

答案 0 :(得分:0)

要执行此类操作,您需要在Web服务器和python脚本之间使用CGI层,因为Web服务器无法直接使用它们。通常使用以下后端堆栈:

Scripts with business logic (python/perl/php) -> CGI layer (WSGI, uWSGI, etc..) -> Webserver (Apache, nginx, etc..)

因此,您收到脚本的内容而不是它的输出,因为它没有被执行,只是像文本文件一样读取。