簡體   English   中英

從 python 獲取變量到 js

[英]get variable from python into js

我正在創建一個應用程序,該應用程序根據程序選擇的隨機單詞顯示網頁搜索。 我將字典上傳到 python 以獲取隨機單詞,現在我想將這個單詞放入我的 javascript 代碼中的 src= 中。 我需要的是某種連接兩種語言的占位符

Python

if request.method == 'GET':

    #create an empty dictionary
    d = {}

    key = 0

    #open dictionary file and store it in 'dic'
    with open('dictionaries/nouns.rtf',encoding="utf8", errors='ignore') as dic:
        #read every line and give it a number
        for line in dic:
            value = line.replace('\\', '')
            key += 1
            d[key] = value
        
    #select a random number in the range of the dictionary (and store it in a variable)
    rand = random.randrange(1, len(d) + 1)

    #get the word with that number (and store it in a variable)
    word = d[rand]

    #print(word)

    return render_template('/player.html', word = word)

Javascript

<script>
    let is = document.getElementById('innerSpace');
    query = encodeURI({{word}})
    is.src = `https://www.bing.com/images/search?q=weirdest+${query}&form=QBLH&sp=-1&pq=cats&sc=8-4&qs=n&cvid=20659354CDFD49C6B03ED29A4F35EC64&first=1&tsc=ImageBasicHover`
</script>

要獲取從 Python 到 Javascript 的隨機生成的單詞,您需要從您的視圖返回 JSON 響應。

from django.http import JsonResponse

if request.method == 'GET':
    ...
    data = { 'word': word}
    return JsonResponse(data)

然后,您可以使用 AJAX 或 Fetch 訪問 JavaScript 中的word 我將以 Jquery 為例。

let is = document.getElementById('innerSpace');
 $.ajax({
        url: '/URL_for_your_view/',
        action: 'GET',
        // when the server returns data, the success method is run
        success: function (data) {
              query = encodeURI({{data.word}})
              is.src = `https://www.bing.com/images/search?q=weirdest+${query}&form=QBLH&sp=-1&pq=cats&sc=8-4&qs=n&cvid=20659354CDFD49C6B03ED29A4F35EC64&first=1&tsc=ImageBasicHover`
        }})

現在,此解決方案的問題是view將不再返回模板player.html ,這在您的代碼中似乎必不可少。

return render_template('/player.html', word = word)

據我所知,您不能在同一視圖中返回 JSON 響應和模板。 不可能。

所以你需要使用 JavaScript 重新創建播放器。 success方法里面的player.html代碼和 append 到 DOM。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM