可以将Python、AJAX与CGI一起使用吗
我想做一个网页,点击一个按钮后,通过AJAX从一个Python脚本获取一个字符串,然后把这个字符串显示在一个段落的HTML元素里。
我知道理论上可以用Python、WSGI和AJAX来实现这个功能,但这太复杂了。我对CGI和Python比较熟悉。
那么,我能不能用CGI来实现上面的功能呢?
如果可以的话,Python脚本的工作方式是不是和用CGI提供页面时一样?
这个方法不行:
import cgitb; cgitb.enable()
import cgi
import os
print "Content-Type: text/html\n"
input_data = cgi.FieldStorage()
print "hello"
当我在网页上点击按钮时,什么都没有发生,而我的CGI服务器(处理CGI页面请求时运行正常)却给我返回了一个HTTP 501错误。
我的HTML和JavaScript代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
<!--
function onTest( dest, params )
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById( "bb" ).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST",dest,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send( params );
}
-->
</script>
</head>
<body>
<p id="bb"> abcdef </p>
<a href="javascript:onTest('aaa.py', '')">Click it</a>
</body>
</html>
4 个回答
0
4
当然,如果你想的话,可以使用老旧的CGI。你的代码在我这儿运行得很好。(当点击链接时,“abcdef”会变成“hello”。)
你可能在设置上有一些简单的错误。我建议你检查一下测试脚本的文件权限(要设置为a+rx),这可能是你忽略的地方。另外,我假设你的CGI脚本顶部有一行“#!/usr/bin/env python”(或者类似的),在你上面的例子中这行是缺少的。
5
这里有三个文件:[my.html, myCGI.py, myPyServer.py]。在Windows XP系统中,我把它们放在同一个文件夹里,然后双击myPyServer.py,结果一切都运行得很好。
my.html和你的html文件差不多,只是:
yours: <a href="javascript:onTest('aaa.py', '')">Click it</a>
mine: <a href="javascript:onTest('/myCGI.py', 'x=7')">Click it</a>
myCGI.py和你的文件也很相似。
import cgitb; cgitb.enable()
import cgi
import os
input_data = cgi.FieldStorage()
if input_data:
print "Content-Type: text/html\n"
print "hello"
else:
f = open('my.html', 'r'); s = f.read(); f.close()
print "Content-Type: text/html\n"
print s
myPyServer.py
import CGIHTTPServer
import BaseHTTPServer
import sys
class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
cgi_directories = ["/"] #make sure this is where you want it. [was "/cgi"]
PORT = 8000
httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
# see effbot http://effbot.org/librarybook/thread.htm
def runserver():
print "serving at port", PORT
httpd.serve_forever()
import thread
thread.start_new_thread(runserver, ())
print "opening browser"
import webbrowser
url = 'http://127.0.0.1:8000/myCGI.py'
webbrowser.open_new(url)
quit = 'n'
while not(quit=='quit'):
quit = raw_input('\n ***Type "quit" and hit return to exit myPyServer.*** \n\n')
print "myPyServer will now exit."
sys.exit(0)