烧瓶传递json和render_template

时间:2018-11-09 22:37:41

标签: javascript json flask flask-login flask-session

我是一个新开发人员,我有一个带有数据的Json对象,我正在尝试使用render_template

将其传递到某个页面

我已经看到了几个答案,但是由于某些原因,它们都没有为我工作

我知道Javascript和Flask之间的连接是牢固的,因为我可以在JS中的Onload函数中使用console.log(“ string”),但似乎无法识别我通过渲染模板传递的任何内容

到目前为止我尝试过的东西

将json对象保存为变量,并将其与渲染模板一起传递。

    x = {"Success": True , "Msg":" lets try to get jinja to work - email {{ current_user.email }} " , "displayname":current_user.name}
    t = "test"
    return render_template("index.html", x=x ,t=t)

在JS上

document.addEventListener('DOMContentLoaded' , function () {
console.log("loaded");


const onStay = new XMLHttpRequest();
onStay.open('post' , "stay" , true);
onStay.send(null);

onStay.onload = ()=>{

console.log("i got response from flask ... onstay.onload , cheers !");
//console.log(x);
var  rt = t;
console.log(rt);
var resStay = JSON.parse(x.responseText);
var tt = JSON.parse('{{ x | tojson | safe}}');

所以我也在测试是否可以传递jinja2代码或flask_login代码,将其实际保存在某种变量中并用JS进行响应

第二次尝试是尝试对方法进行jsonify并进行解析

在python上:

X = jsonify({"Success": True , "Msg":" lets try to get jinja to work - 
email {{ current_user.email }} " , "displayname":current_user.name})
return render_template("index.html", X=X)

在JS端:

 onStay.onload = ()=>{
 var res = JSON.parse(reqSignup.responseText);
 console.log("res  === " , "\n" , res );

我得到的输出是

JavaScript.js:11 i got response from flask ... onstay.onload , cheers !
JavaScript.js:13 Uncaught ReferenceError: t is not defined
    at XMLHttpRequest.onStay.onload (JavaScript.js:13)
onStay.onload @ JavaScript.js:13
load (async)


JavaScript.js:191 qwe@qwe.qwe 
 qwe
JavaScript.js:313 DATA   =  FormData {}

1 个答案:

答案 0 :(得分:0)

问题是您正尝试直接从JavaScript访问变量。您需要做的是使用Jinja在Flask模板中使用这些变量,并在其中调用您的JavaScript。

一个经典示例是放置一个按钮,其按钮为onclick = YourFunction(x)。调用该函数时,它将传递变量中具有的值。

您应该使用默认的Flask模板引擎Jinja,但是如果您更喜欢我开发的模板引擎,那么Sucuri就是这样。

希望这会有所帮助。

相关问题