从浏览器将数据发送到一个Python CGI脚本处理我有以下使用纯JavaScript
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<body>
<script type="text/javascript">
var httprequest=new XMLHttpRequest();
httprequest.open("POST","hello.cgi",true);
httprequest.onload=function(){
if(httprequest.status==200){
alert("");
}// end of if
}//end of onload
var content={"hello":"world"};
httprequest.send(JSON.stringify(content));
alert(httprequest.responseText)
</script
</body>
</html>
</doctype>
在这种情况下,我尝试发送数据{“你好”的HTML测试文件:”世界”};为Python CGI脚本
这是我的Python脚本与从<form>
html标记
#!/usr/bin/python
try:
import sys
import cgi
import traceback
print("Content-type: text/html\n\n")
print "<h1>YES</h1>"
formData = cgi.FieldStorage()
print(formData)
print(s)
except Exception as e:
print(e.message)
print(traceback.print_exc())
提交的数据。当我发送数据{"hello":"world"}
效果很好,我的浏览器提示框显示没有返回的数据来自cgi脚本。
正如cgi脚本中所反映的,我试图打印“YES”并打印从javascript发送的数据。
我发现与使用$.ajax
这样做有几个问题,但整个使用XMLHttpRequest()
问题
我怎样才能将数据发送到一个Python CGI脚本的方法还没有来从我的浏览器使用纯JavaScript处理(无jquery)
你的'alert()'发生在HTTP请求完成之前。这是一个**异步**操作。 – Pointy
好吧..我试试这个,看看这是如何工作的...我相对较新的JS – repzero
@ Pointy ..我移动了“alert(httprequest.responseText)”,并将其放在onload函数中,这可以工作.can你发布了一个答案,并详细阐述了与上述代码有关的异步操作..非常感谢.....我不确定我是否理解为什么它不起作用的原因 – repzero