python JsException(TypeError:无法获取)

esyap4oy  于 2023-06-28  发布在  Python
关注(0)|答案(3)|浏览(208)

当我尝试将pyscript源代码导入到HTML时,它显示“JsException(TypeError:无法获取)”错误。

helloworld.py

print("Hello World")

testPyscript.html

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    <title></title>
</head>
<body>
    <py-script src="helloworld.py">
        ("Another Text Test")
    </py-script>
</body>
</html>
7ivaypg9

7ivaypg91#

我遇到了同样的问题,在这里找到了答案:PyScript: Loading Python Code in the Browser
问题是<py-script src="helloworld.py">不支持加载本地文件,你需要一个服务器的浏览器来加载它...
进入保存文件的文件夹并运行python -m http.server 80,然后在浏览器上转到localhost/testPyscript.html
希望有帮助

5lhxktic

5lhxktic2#

出于某种原因,您的目录包含helloworld.py和testPyscript.html需要在localhost中运行,在vsCode中打开文件夹并从扩展安装live server,然后在右下角按Go Live。您将被定向到默认浏览器,其中包含来自www.example.com的预期输出helloworld.py

pu3pd22g

pu3pd22g3#

我也遇到过类似的问题,所以我写了这篇文章。如前所述,您必须从本地托管服务器托管项目目录。
link to original post:Error "JsException (TypeError: Failed to fetch)" while trying to run using Python and HTML
定义脚本环境路径,必须放在head标签中。

<py-env>
        - paths:
          - ./pytest.py
      </py-env>

下面是检索python输出并注入html格式的示例代码。代码示例:

index.html

<html>
    <head>
      <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
      <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
      <py-env>
        - paths:
          - ./pytest.py
      </py-env>
    </head>
  <body>
    <h1>Update HTML from PYTHON</h1>
    <b> <label id="output"></label></b>
    <py-script>
      from pytest import function
      pyscript.write('output', function())
    </py-script>
  </body>
</html>

www.example.com

def function():

    output = 'CONGRATS!'

    return ('Your Data has been extracted from a python script: '+''.join(output))

相关问题