flask 在 html 中 呼叫{{ }} 函數 之後 無法用javascirpt 變數去指向陣列位置

195 views
Skip to first unread message

Frank Liou

unread,
Dec 17, 2014, 10:49:27 PM12/17/14
to pyth...@googlegroups.com
目前遇到了個問題

我在html 撰寫過程中 想要呼叫從python 帶過來的參數
        return render_template('productshare.html'ProductImage= pic, PictureLenth=PictureLenth)

PictureLenth 是pic 陣列長度
想透過兩三秒執行一次函式來達到幻燈片效果
不過

{{  }}裡面不認我"now"這個變數

請問各位高手有什麼更好的方法嗎??

lenth = {{ PictureLenth }}-1;
now = 0;

function t_setInterval() {
window.intervalParam = window.setInterval(function() {
var date = new Date();
   if (lenth>now)
   {now = now + 1;}
   else
   {now = 0;}
    var img = document.getElementById("image");
    img.src="data:image/png;base64, {{ ProductImage[now] }}";
    return false;
}, 4000);
}


sj l

unread,
Dec 18, 2014, 1:17:04 AM12/18/14
to pyth...@googlegroups.com
flask是在后端执行完的, js是在浏览器端执行的, 你这样写是错的.
var ProductImage = {{ProductImage}}, now = 0;

img哪里: img.src = "............, " + ProductImage[now];

--
這是 Google 網上論壇針對「python.tw」群組發送的訂閱通知郵件。
如要取消訂閱這個群組並停止接收來自這個群組的郵件,請傳送電子郵件到 pythontw+u...@googlegroups.com
如要在這個群組張貼留言,請傳送電子郵件到 pyth...@googlegroups.com
請前往以下網址造訪這個群組:http://groups.google.com/group/pythontw
如需更多選項,請前往:https://groups.google.com/d/optout

knot

unread,
Dec 22, 2014, 5:47:52 AM12/22/14
to pyth...@googlegroups.com

你傳string 給python,python再依據所知的變數把string轉為變數,當你沒告訴python now是什麼,
python當然不懂囉,這就像

product = range(10)
eval("product[now]")

Traceback (most recent call last):
  File "<pyshell#1>", line 2, in <module>
    eval("product[now]")
  File "<string>", line 1, in <module>
NameError: name 'now' is not defined

把now render成數值,就解了
 img.src="data:image/png;base64, {{ ProductImage[0] }}"
.
.
 img.src="data:image/png;base64, {{ ProductImage[n] }}"


Frank Liou於 2014年12月18日星期四UTC+8上午11時49分27秒寫道:
Reply all
Reply to author
Forward
0 new messages