简体   繁体   中英

Sending a python list of tuples to JavaScript array of arrays not working

I'm trying to send a python list of tuples to a javascript array but for some reason, it doesn't work.

python code

import json
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def stock_table():
    if request.method == "POST":

        data = [('abc','efg','hij', "klm"), ('nop','qrs','tuv', "wxyz")]
        string_data="'"
        string_data+=str(json.dumps(data))
        string_data+="'"
        return render_template('index.html', result=string_data)
    
    else:
        return render_template('index.html')

if __name__ == '__main__':
app.run()

string_data comes out as: '[["abc", "efg", "hij", "klm"], ["nop", "qrs", "tuv", "wxyz"]]'

javascript code

<!DOCTYPE html>
<html>
<body>
    <h3> Show stock pie graph </h3>
    <form action="{{ url_for('stock_table') }}" method="post">
        Enter User Name:  <input type = "text" name= "user_name" />
            <input type="submit"  value="Go!">
            <p id="result"></p>

            
    </form>

    <script> 
    var array_start ="{{ result }}";
    arrayOfArrays = JSON.parse(array_start);
    document.getElementById("result").innerHTML = arrayOfArrays;
    </script>

</body>
</html>

when I run the program it doesn't show any errors, but it doesn't display the result.

I also tried using the string that I made in javascript by just copying it and it worked!

I think the problem is that the JSON.parse function doesn't work on the data I send from python when there is a string included in the tuple,when it's just numbers it works just fine.

Any help would be appreciated!

I'm not sure what you're up to.

You can use a jinja2 filter to convert the data into a JSON compliant string. It is also important to pay attention to the quotation marks.

@app.route('/', methods=['GET', 'POST'])
def stock_table():
    data = []
    if request.method == "POST":
        data = [('abc','efg','hij', 'klm'), ('nop','qrs','tuv', 'wxyz')]
    return render_template('index.html', data=data)
<p id="output">{{ data | tojson | safe }}</p>
<p id="result"><p>
<script type="text/javascript">
  const data = '{{ data | tojson | safe }}';
  console.log(JSON.parse(data));

  document.getElementById('result').innerHTML = data;
</script>

If you want to use AJAX you can use jsonify within your route to respond with the result in JSON format. You can find an example here . Possibly you should rather use the submit event of a form there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM