0

this is my flask python code:

@app.route('/ques/<string:idd>',methods=['GET', 'POST'])
def ques(idd):
    print idd

Javascript code:

var counts = {{ test|tojson }};
var text = "";
var texts= "";
for (i = 1; i < counts.length; i=i+2){
    texts=counts[i-1];
    document.write("<a href=\"{{url_for('ques',idd=texts)}}\">"+counts[i]+"</a></br></br>");
}

how to pass idd to python function?

agnes
  • 11
  • 1
  • 5

1 Answers1

0

Jinja gets rendered on the server so you can't mix and match it with javascript. Try something like this:

var counts = {{ test|tojson }},
    // before the HTML file gets to the browser this line will be:
    // baseURL = "/ques/REPLACE"
    baseURL = "{{ url_for('ques', idd='REPLACE') }}";

for (i = 1; i < counts.length; i = i+2) {
    var url = baseURL.replace('REPLACE', counts[i-1]);
    document.write("<a href=\"" + url + "\">" + 
                   counts[i] + "</a></br></br>");
}

Otherwise you'll need to build the URL directly in Javascript.

A better way of doing it would be to use request arguments:

@app.route('/ques/')
def ques():
    # url is: /ques/?idd=ABC
    idd = request.args.get('idd', default='', type=str)
    print idd

Javascript:

var counts = {{ test|tojson }},
    baseURL = "{{ url_for('ques') }}";

for (i = 1; i < counts.length; i = i+2) {
    var url = baseURL + '?idd=' + counts[i-1];
    document.write("<a href=\"" + url + "\">" + 
                   counts[i] + "</a></br></br>");
}
abigperson
  • 5,252
  • 3
  • 22
  • 25