1

I am doing a project that needs to use dynamic javascript files and to use ajax to post some data. I want to do post and get action in the same javascript file.

I put my js file in templates directory and in javasctript I have code like this:

$.ajax({
            url:'/location.js',
            type:'post',
            data:{'appid':this.appId},
            datatype:'json',
            success:function(data){
                console.log('successpost');
                window.alert('{{ag}}');
                }
        });

in flask I have code like this:

@application.route('/location.js', methods=['POST', 'GET'])
def test():
    appid = request.form.get('appid')
    ag = dao.has_agent(appid)
    return render_template('location.js', ag=ag)

and ag is the data I want to use in location.js. And ag is an int-type parameter. If I use print(ag) I can see the value of ag But I found that I cannot use {{ag}} to receive data in the javascript file and it will alert 'None' instead. I wonder whether it is a wrong try to do like this. Is there any better way to solve this problem?

rose
  • 11
  • 1
  • Kindly include `location.js`'s code in the question. Also, you are trying to use [Jinja's Template Syntax](https://jinja.palletsprojects.com/en/3.1.x/templates/#variables) in JavaScript, which will not work. – Shri Hari L May 28 '23 at 05:09
  • @shri-hari-l you can indeed use Jinja's template syntax in JavaScript. – Rob May 28 '23 at 18:38
  • I'm unable to reproduce the error on my machine (ag passes successfully for me). It seems like you have everything set up correctly. Like Shri said, editing your post to include a more complete `location.js` would be helpful. – Rob May 28 '23 at 18:51
  • 1
    Hi I have solved this problem, cause the flask will conduct GET action and then POST action, so I found that if I want to response to GET and POST in location.js, I need to split my code to @application.route('/location.js', methods=['GET']) and @application.route('/location.js', methods=['POST']) – rose May 29 '23 at 06:08
  • Right on. Just fyi you can also use `application.get('/location.js')` and `application.post('/location.js')` to make things a little cleaner. Or, you can also still have both methods in one function like you did originally, just add an `if` statement to check which method is being called, eg. https://stackoverflow.com/a/42018751/19224040 – Rob May 29 '23 at 08:18

0 Answers0