如何使用 Transcrypt 读取 URL 的内容? urlopen() 位于何处?

How can I read the contents of an URL with Transcrypt? Where is urlopen() located?

在 Transcrypt 中,我尝试从 URL 读取 JSON 数据,所以我尝试:

import urllib.request    
data = urllib.request.urlopen(data_url)

但我收到错误“导入错误,找不到 [...] urllib.request”。所以urllib.request好像不支持;奇怪的是,尽管顶级 import urllib 有效,但是我没有使用 urlopen() 函数...

知道 urlopen() 在 Transcrypt 中的什么位置吗?还是有另一种方法来检索 URLs?

我认为 Transcrypt 没有可用的 Python urllib 库。您将需要使用相应的 JavaScript 库。我更喜欢 axios,但你也可以只使用内置的 XMLHttpRequest() 或 window.fetch()

这是一个 Python 函数,您可以合并它使用 window.fetch():

def fetch(url, callback):
    def check_response(response):
        if response.status != 200:
            console.error('Fetch error - Status Code: ' + response.status)
            return None
        return response.json()

    prom = window.fetch(url)
    resp = prom.then(check_response)
    resp.then(callback)
    prom.catch(console.error)

只需从您的 Python 代码中调用此获取函数并传入 URL 和回调以在收到响应后使用它。