首页 > 解决方案 > ajax 函数在不应该时仍然刷新页面

问题描述

#index.js

const detail = document.getElementById('btc-price')
    
function loadPrices() {
  var xhr = new XMLHttpRequest()
  xhr.open('GET', 'data.json', true)
    
  xhr.onload = function() {
    if (this.status == 200) {
      var data = JSON.parse(this.responseText)
      detail.textContent = data.cryptos.BTC
    }
  }

  xhr.send()
}
    
setInterval(loadPrices(), 2000)

#index.html

<body>
  <p>BTC: <span id="btc-price"></span></p>

  <script src="index.js"></script>
</body>

#main.py

import cryptocompare
from time import sleep
import json
    
count = 0
while True:
  coins    = cryptocompare.get_price(['BTC', 'ETH', 'DOGE', 'ADA', 'XLM'], 'USD')
  name_lst = [x for x in coins.keys()]
 price_lst = [x.get('USD') for x in coins.values()]
    
 prices    = dict(zip(name_lst, price_lst))
 json_dict = {'cryptos': prices}
    
 with open('data.json', 'w') as f:
   data = json.dump(json_dict, f)
    
   with open('data.json') as f:
     info   = json.load(f)
     count += 1
     print('finished', count)
     sleep(3)

我有一个函数可以从 main.py 不断更新的 data.json 文件中加载加密货币的价格,这一切都很好,但是当价格更新时,页面会刷新,这在这种情况下不应该发生,我不知道它为什么会这样,任何帮助表示赞赏!

标签: javascriptpythonajax

解决方案


推荐阅读