【问题标题】:List returned from python to Ajax get strange characters从python返回到Ajax的列表得到奇怪的字符
【发布时间】:2021-06-08 15:54:35
【问题描述】:

如何正确地将列表从 Python 返回到 Ajax,返回时输出看起来很奇怪。

app.py

@app.route('/_get_comUpdate/', methods=['POST'])
def _get_comUpdate():
    comNr = request.form.get('comNr')
        
    com_result = COMPort("ON","COM255",comNr)
    print(com_result)

    return jsonify({'data': render_template('com_response.html', com_result = com_result)})

com_response.html

{{com_result}}

index.html

$.ajax({
    url: "/_get_comUpdate/",
    type: "POST",
    success: function(resp){
        com_result = (resp.data);
        alert(com_result); 
        }
    });

python 中列表的输出:

['ON', 'OFF', 'OFF', 'OFF', 'OFF', 'OFF']

返回给 Ajax 的列表输出:

['ON', 'OFF', 'OFF', 'OFF', 'OFF', 'OFF']

【问题讨论】:

  • 而不是request.form.get你试过request.form.getlist吗?
  • 您正在通过您尚未发布的 com_response.html 发送数组,因此很难给出明确的答案,但它可能在某处。我使用的 Django 比烧瓶多,但我猜它正在逃避那里的东西。我希望您可以使用一些过滤器或标志将其标记为安全,这样它就不会逃逸。

标签: javascript python ajax flask


【解决方案1】:

对于可能不准确的食谱,我很抱歉,因为我看不到您的所有代码。我猜原因是在指定 UTF-8 编码

可能是后端..

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from flask import Flask
from flask.ext.restful import Api
from flask.ext.restful.representations.json import output_json
output_json.func_globals['settings'] = {'ensure_ascii': False, 'encoding': 'utf8'}
app = Flask(__name__)
api = Api(app)
...

可能是前端

<html> <head> <meta charset="utf-8">

可以运行应用程序

set PYTHONIOENCODING=UTF-8

而且,你能用 json.dumps 代替 jsonify 吗?希望对你有所帮助)

【讨论】:

  • 是的,似乎是某种编码问题。我会继续调查。 =)
  • 尝试在列表中显示结果,例如 ['your result']。那么它是UTF-8或latinic会更明显。对不起,一个不知道,怎么说re-re-utf8
  • 这些时刻在 IDE 中显而易见
  • 我什至不确定是否可以通过这种方式返回一个列表,所以我返回了一个逗号分隔的字符串并将其拆分为 javascript 中的一个数组。
猜你喜欢
  • 1970-01-01
  • 2020-01-24
  • 2019-11-14
  • 1970-01-01
  • 1970-01-01
  • 2019-07-05
  • 2017-07-04
  • 2018-03-11
  • 2019-07-27
相关资源
最近更新 更多