我想要一个单击按钮的网页,通过使用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"
Run Code Online (Sandbox Code Playgroud)
当我在我的页面中单击我的按钮时,没有任何反应,我的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>
Run Code Online (Sandbox Code Playgroud)
这里有3个文件[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>
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8893 次 |
| 最近记录: |