0

How do I return a list correctly from Python to Ajax, the output looks strange when returned.

ap.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); 
        }
    });

Ouput of list in python:

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

Output of list returned to Ajax:

['ON', 'OFF', 'OFF', 'OFF', 'OFF', 'OFF']
Tobbe
  • 55
  • 7
  • instead of `request.form.get` have you tried `request.form.getlist`? – Teejay Bruno Mar 10 '21 at 16:52
  • You are sending the array through the com_response.html, which you haven't posted, so it's tough to give a definitive answer, but it's probably in there somewhere. i've used more Django than flask, but I'm guessing it's escaping things in there. I expect there's some filters or flags you can use to mark it as safe so it doesn't escape. – saquintes Mar 10 '21 at 16:54
  • Check it helpful, https://stackoverflow.com/questions/12435297/how-do-i-jsonify-a-list-in-flask – Jisson Mar 10 '21 at 16:57

1 Answers1

0

Sorry for the possibly inaccurate recipe, because I can't see the all your code. I guess that the reason is in specifying the UTF-8 encoding

May be backend..

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)
...

may be frontend

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

may be run application

set PYTHONIOENCODING=UTF-8

And, can u use json.dumps instead jsonify? hope helped to you)

Blay Wille
  • 46
  • 1
  • 5
  • Yes, it seems to be some kind of encoding problem. I will continue to investigate. =) – Tobbe Mar 10 '21 at 17:13
  • Try displaying the result on a list, for example ['your result']. Then it will be more obvious that it is UTF-8 or latinic. Sorry, a dont know, how say about re-re-utf8 – Blay Wille Mar 10 '21 at 17:49
  • these moments are evident in IDE – Blay Wille Mar 10 '21 at 17:55
  • I'm not even sure it is possible to return a list this way so I returned a comma separated string and split it into a array in the javascript. – Tobbe Mar 10 '21 at 19:03