将webpy与AJAX结合使用
Using webpy with AJAX
我对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
文件夹。
相关文章:
- 将图像上传ajax与表单提交ajax相结合
- 如何将 AJAX 与 JSON 结合使用
- 将post方法与php、ajax和javascript结合使用
- Ajax成功地将表与progressbar结合起来
- ajax和tweenmax的结合
- AJAX:结合上传文件和文本输入代码
- Ajax 将关联数组与表单序列化相结合
- 如何将简单的 JQuery 自动完成语法与对远程数据源(PHP 脚本)的 ajax 调用相结合
- 将多个引导按钮与 jquery Ajax 结合使用
- 结合两个javascript函数来验证表单并通过ajax提交
- 将 IBM watson API 与 jquery 的 $.ajax 结合使用
- Jquery getScript 或 ajax 与 php flush 相结合
- 将Ajax与JSF命令按钮或表单结合使用
- $.ajax与$.ajaxSetup默认设置相结合
- 如何将JsonResponse与ajax结合使用
- 将Ajax与表排序/筛选相结合
- PHP/AJAX -建议替换iFrame与DIV(结合AJAX)
- ajax/PHP (Icecast) -如何结合ajax和PHP
- 关于结合ajax,php和javascript
- 结合AJAX请求来加载带有变量的新页面