将webpy与AJAX结合使用

Using webpy with AJAX

本文关键字:结合 AJAX webpy      更新时间:2023-09-26

我对web开发相对陌生,正在尝试让客户端javascript向服务器上运行的python脚本发送get请求,并让服务器根据该请求返回数据。我试着改编我在网上找到的webpy库的例子,但没有成功。无论何时发送GET请求,XMLHttpRequest()的responseText属性都会返回python文件的文本,而不是数据。任何建议都将不胜感激!

javascript函数:

function sendSerialCommand(selection, command) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            if (command !== 5) {
                document.getElementById("output2").innerHTML = xmlhttp.responseText;
                document.getElementById("output2").style.color = "green";
            } else {
                document.getElementById("output1").innerHTML = xmlhttp.responseText;
                console.log(xmlhttp.responseText);
                document.getElementById("output1").style.color = "green";
            }
        }
    };
    xmlhttp.open("GET", pythonFileName + "?sel=" + selection + "?cmd=" + command, true);
    xmlhttp.send();
}

和测试python脚本:

import web
urls = (
    '/', 'Index'
)
app = web.application(urls,globals())
#MAIN LOOP
class Index:
    def GET(self):
        webInput = web.input()
        return 'message: GET OK!'
if __name__ == "__main__":
        app.run()

诀窍是使用python的CGI库:

#!/usr/bin/python
# Import modules for CGI handling 
import cgi, cgitb 
# Create instance of FieldStorage 
form = cgi.FieldStorage() 
# Get data from fields
first_name = form.getvalue('cmd')
last_name  = form.getvalue('sel')
print "Content-type:text/html'r'n'r'n"
print "Hello %s %s" % (first_name, last_name)

这将捕获GET请求中的密钥和数据,print命令将数据返回到客户端的xmlhttp.responseText属性。

脚本必须放在Web服务器能够执行脚本的文件中。这通常是位于/var/www/etc中的默认/cgi-bin文件夹。