简体   繁体   English

使用XMLHttpRequest的AJAX请求返回本地Python文件的内容,而不是执行它

[英]AJAX request using XMLHttpRequest returns content of local Python file instead of executing it

Web page and Python script are both local in a Raspberry Pi (no internet connection). 网页和Python脚本在Raspberry Pi中都是本地的(没有Internet连接)。

The Python script runs fine when called from the command line. 从命令行调用Python脚本可以正常运行。

JavaScript in the web page uses AJAX to call the Python script: 网页中的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');   

I also tried "GET" with the same results: 我也尝试过“ 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();     

The script is not executed ( I can tell from the log). 该脚本未执行(我可以从日志中看出)。

Am I misunderstanding what AJAX can do? 我是否误解了AJAX可以做什么? Can it not run local scripts? 它不能运行本地脚本吗?

My ultimate goal: to pass a user entry from the web page to the script, to configure the Raspberry Pi. 我的最终目标是:将用户条目从网页传递到脚本,以配置Raspberry Pi。

EDIT: Again, everything is local: no server, no internet, no HTTP. 编辑:同样,一切都是本地的:没有服务器,没有Internet,没有HTTP。

If the answer is "no, you can't do that without a server" that's all I need to hear, and I'll look at using a port 80 instead to achieve what I want. 如果答案是“不,没有服务器,您将无法做到”,这就是我所需要听到的,我将考虑使用端口80来实现我想要的功能。

Python (in response to HTTP requests) is executed by a web server. Python(响应HTTP请求)由Web服务器执行。

If you fetch from file:// URLs, you will either get an error or raw content, depending on your browser. 如果从file:// URL获取,则将显示错误或原始内容,具体取决于您的浏览器。

You can run any HTTP server that can call Python scripts (using Python, or a CGI variant) on any port. 您可以在任何端口上运行可以调用Python脚本(使用Python或CGI变体)的任何HTTP服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM