從瀏覽器將數據發送到一個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