我将尝试通过ajax POST请求从Python传递字符串到Javascript,但是我遇到了严重的困难。
我尝试使用JSON和不使用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
但是我也得到了空字符串。
您能否给我一些处理这个问题的建议?非常感谢!