AJAX请求返回Python的文件的内容,而不是执行它

问题描述:

网页和Python脚本都是在树莓派(无互联网连接)本地。AJAX请求返回Python的文件的内容,而不是执行它

从命令行调用时,Python脚本可以正常运行。

JavaScript的网页中使用AJAX调用Python脚本:

var xmlhttp = new XMLHttpRequest();  
    xmlhttp.onreadystatechange=function() { 
     alert('readyState: '+ xmlhttp.readyState)  // Returns: 4 
     alert('status: '+ xmlhttp.status)    // Returns: 0 
     alert('statusText: '+ xmlhttp.statusText)  // Returns: (Blank) 
     alert('responseText: '+ xmlhttp.responseText) // Returns contents of script 
    } 
    xmlhttp.open("POST", "myscript.py", true); 
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xmlhttp.send('test'); 

我也试过 “GET” 具有相同的结果:

var xmlhttp = new XMLHttpRequest();  
    xmlhttp.onreadystatechange=function() { 
     alert('readyState: '+ xmlhttp.readyState)  // Returns: 4 
     alert('status: '+ xmlhttp.status)    // Returns: 0 
     alert('statusText: '+ xmlhttp.statusText)  // Returns: (Blank) 
     alert('responseText: '+ xmlhttp.responseText) // Returns contents of script 
    } 
    xmlhttp.open("GET", "myscript.py", true); 
    xmlhttp.send();  

不执行脚本(我可以从日志中告诉)。

我误解了AJAX的功能吗?它可以不运行本地脚本?

我的最终目标:从网页的用户条目传递给脚本,配置树莓派。

编辑:再次,一切都是地方:没有服务器,没有互联网,没有HTTP。

如果答案是“不,你不能这样做,没有一个服务器”这就是我需要听到,我会看看使用80端口,而不是达到我想要的。

+1

AJAX只是发送HTTP请求。您需要将您的服务器配置为以您想要的方式处理该请求。 – SLaks

+0

可以这样做。但是你不能通过http在服务器上执行任意代码。您需要在您的服务器上运行一个Web服务器(在这种情况下为raspberry-pi),并设置特定的终结点(urls)。一个常见的选择是使用名为[flask]的python web框架(http://flask.pocoo.org/)。有许多关于在rasberry pi上使用烧瓶的指南和教程。只是谷歌它。 –

+0

@SLaks“您需要配置您的服务器”。没有服务器。正如我所说,一切都是本地的,没有互联网,没有服务器。 –

Python(响应HTTP请求)由Web服务器执行。

如果从file://网址抓取,你要么得到一个错误或原始内容,具体取决于您的浏览器。

您可以运行,可以在任何端口上调用Python脚本(使用Python或CGI变体)的任何HTTP服务器。