【问题标题】:Passing a string from Python to Javascript将字符串从 Python 传递到 Javascript
【发布时间】:2015-10-10 20:12:12
【问题描述】:

我正在尝试通过 ajax POST 请求将字符串从 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,比如 蟒蛇

 print "heyyyyy"

Javascript

 alert(response) //case of success

但我也得到了一个空字符串。

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

【问题讨论】:

  • 你不应该使用打印。

标签: javascript jquery ajax json python-2.7


【解决方案1】:

您可能想比较代码CGIHTTPRequestHandler run php or python script in pythonhttp://uthcode.blogspot.com/2009/03/simple-cgihttpserver-and-client-in.html 的两个sn-ps。

没有足够的代码来判断您的请求处理代码在哪里,但如果它在继承自 CGIHTTPRequestHandler 的类中,那么您需要使用 self.wfile.write(json.dumps(out)) 等。

【讨论】:

    【解决方案2】:

    我设法使用 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);
    

    这很好用,我认为它非常易读和简单!

    【讨论】:

      【解决方案3】:

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

      print 只会在 python 的控制台中显示它,就像在 javascript 中的 console 一样。

      【讨论】:

      猜你喜欢
      • 2012-08-23
      • 2020-05-28
      • 2011-11-22
      • 2021-12-11
      • 2014-02-04
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多