简体   繁体   中英

How to pass mongodb returned values to javascript array?

I am using flask to render html template.I want to store all items returned by pymongo query into a java script array.I created an array c[] which is empty first.And i used for loop of flask to iterate through returned items of pymongo query and i am pushing it to array c.

I tried some answers of stackoverflow but it dint match understanding of my question

my html code is here:home.html

<html>
    <head>
        <title>ii</title>
  </head>
<script>
var c=[]
{% for todo in collection %}
c.push{{todo["q"]}};
{% endfor %}

</script>
</body>
</html>

my flask file:-

from flask import Flask, render_template,json
from pymongo import MongoClient
from bson import json_util,ObjectId

app = Flask(__name__) 
mongo_object = MongoClient("localhost", 27017)
app.debug= True
db = mongo_object['test']
collection = db['myc']
@app.route('/')
def index():
    return render_template('home.html')


@app.route('/find',methods=['GET', 'POST']) 
def pymongo_data_display():
    my_data = collection.find()
    a1="active"
    return render_template('home.html',a1=a1,collection=my_data,t="hi",h="hoho")
    '''
    if not my_data:
        return 'no data'
    else:        
        return my_data
    '''

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

it gives nothing.But can anyone suggest what to do here?

There are couple of things:

  1. Is my_data non-empty where you provide it to render_template ? What is the structure of the data?
  2. What is the value of todo["q"] in the template? Is it a number or a string? If the latter, you will need to wrap it in quotes before pushing into the JavaScript array.
  3. You are missing parentheses in c.push{{todo["q"]}}; .

Let's say that you need to store list of strings in the JavaScript array (ie you need to quote the values before pushing then into the array). Then you need to define custom filter to achieve it. Here's complete example:

import jinja2                                                                   

def quote(value):                                                               
    return '"{}"'.format(value)                                                 

env = jinja2.Environment()                                                      
env.filters['quote'] = quote                                                    


template = env.from_string("""                                                  
<script>                                                                        
var c = [];                                                                     
{% for item in data %}                                                          
    c.push({{ item.q|quote|safe }});                                            
{% endfor %}                                                                    
</script>                                                                       
""")                                                                            

data = [{'q': 1}, {'q': 2}, {'q': 3}]                                           
print(template.render(data=data))

This works:

home.html file:

<html>
<head>
<title>ii</title>
<script>
    function populateMyDiv(){
        var ul=document.createElement('ul');
        {% for name in collection %}
            var li=document.createElement('li');
            ul.appendChild(li);
            li.innerHTML=li.innerHTML + "{{name}}";
        {% endfor %}
        document.getElementById("test").appendChild(ul);
    }
</script>
</head>
<body onload="populateMyDiv()">
    <div id="test"></div>
</body>
</html>

test.py file:

from flask import Flask, render_template
from pymongo import MongoClient
import json
app = Flask(__name__)

mongo_obj=MongoClient("localhost", 27017)


@app.route('/')
def hello_world():
    db = mongo_obj['your_database']
    collection = db['your_collection']
    temp = collection.find()
    my_data = []
    for x in temp:
        my_data.append(x['name'])
    return render_template('home.html',collection=my_data)

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