我想通過ajax POST請求從Python傳遞一個字符串到Javascript,但我發現了嚴重的困難。從Python傳遞一個字符串到Javascript
我已經嘗試使用和不使用JSON。
下面的代碼
JAVASCRIPT
$.ajax({
url: url, #url of the python server and file
type: "POST",
data: {'data1': "hey"},
success: function (response) {
console.log(" response ----> "+JSON.parse(response));
console.log(" response no JSON ---> " +response);
},
error: function (xhr, errmsg, err) {
console.log("errmsg");
}
});
的Python
import json
print "Access-Control-Allow-Origin: *";
if form.getvalue("data1") == "hey":
out = {'key': 'value', 'key2': 4}
print json.dumps(out)
結果是一個空的JSON。當我在JavaScript中執行類似JSON.parse的操作時,出現輸入錯誤的意外結束,並且當我嘗試獲取響應數據的長度時,我得到的大小爲0. 我想應該會出現客戶端的某些問題服務器通信(我使用CGIHTTPServer)或者可能是python或javascript期望的數據類型有問題。
我也試過沒有JSON,喜歡的東西 的Python
print "heyyyyy"
的Javascript
alert(response) //case of success
,但我也得到一個空字符串。
您能否給我一些處理這個問題的建議? 非常感謝!
你不應該使用打印。 – rolodex