从Python传递字符串到Javascript

3

我将尝试通过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

但是我也得到了空字符串。

您能否给我一些处理这个问题的建议?非常感谢!


你不应该使用print。 - rolodex
3个回答

1

1
我使用Django框架中的HTTPResponse方法成功解决了这个问题。 现在,Python会用JSON回复客户端,就像这样:
from django.http import HttpResponse
...
data = {} 
data['key1'] = 'value1' 
data['key2'] = 'value2' 
.....
response = HttpResponse(json.dumps(data), content_type = "application/json")      
print response; 

JavaScript(检索和读取JSON)

success(response) 
     alert(JSON.stringify(response));

如果我只想发送一个字符串或整数而不是JSON
PYTHON(无JSON)
response = HttpResponse("ayyyyy", content_type="text/plain")
print response

JAVASCRIPT(获取字符串或值)

success: function (response) {
    alert(response);

这个很好用,而且在我看来非常易读和简单!

0

你应该使用return json.dumps(out)而不是print json.dumps(out)

print仅会在Python控制台中显示,就像Javascript中的console一样。


json.dumps(out) 只是将 out 转换为字符串,没有其他作用。看起来使用 print 是正确的方法 http://uthcode.blogspot.com/2009/03/simple-cgihttpserver-and-client-in.html - bbill
抱歉,应该加上 return - rolodex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接