使用纯 javascript 将数据发送到 python cgi 脚本以从浏览器进行处理
send data to a python cgi script for processing from browser using pure javascript
我有一个 html 测试文件,其中包含以下内容
<!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>
在这种情况下,我尝试发送数据 {"hello":"world"};到 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()
的方法
问题
如何使用纯 javascript(无 jquery)[ 将数据发送到 python cgi 脚本以从我的浏览器进行处理=18=]
您正在执行的 HTTP 请求是在它自己的时间发生的。对 httprequest.send()
的调用启动了 操作,但是该函数调用 returns 几乎是立即进行的,而且肯定是在远程服务器响应之前。这种 异步 行为是 JavaScript 环境中的一个基本事实。
"onload" 回调的全部原因是让您可以编写在 HTTP 请求实际完成时发生的代码。当结果可用时,浏览器将使用结果 调用该函数 。那可能在 100 毫秒或 10 秒内;这完全取决于服务器和网络。
我有一个 html 测试文件,其中包含以下内容
<!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>
在这种情况下,我尝试发送数据 {"hello":"world"};到 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()
问题
如何使用纯 javascript(无 jquery)[ 将数据发送到 python cgi 脚本以从我的浏览器进行处理=18=]
您正在执行的 HTTP 请求是在它自己的时间发生的。对 httprequest.send()
的调用启动了 操作,但是该函数调用 returns 几乎是立即进行的,而且肯定是在远程服务器响应之前。这种 异步 行为是 JavaScript 环境中的一个基本事实。
"onload" 回调的全部原因是让您可以编写在 HTTP 请求实际完成时发生的代码。当结果可用时,浏览器将使用结果 调用该函数 。那可能在 100 毫秒或 10 秒内;这完全取决于服务器和网络。