确实和 JS 一样简单,只是使用 Python 语法:
def read_file():
xmlhttp= __new__ (XMLHttpRequest())
xmlhttp.open('GET', 'https://github.com/QQuick/Transcrypt/blob/master/README.rst', False);
xmlhttp.send()
console.log(xmlhttp.responseText)
在你的例子中是:
XHR = __new__ (XMLHttpRequest())
XHR.open("POST", "https://example.com/cors.php")
注意__new__ () 函数。在 JavaScript 中,它应该是 new 运算符,但 Python 语法不允许这样做。
如果你想完全避免__new__ (),你可以将XMLHttpRequest封装成一个真正的Python类(它现在是一个JS函数),但没有必要。
见
http://www.transcrypt.org/docs/html/special_facilities.html#creating-javascript-objects-with-new-constructor-call
关于使用或避免__new__ () 的一般说明。
您也可以使用 JQuery,如下面更大的示例:
__pragma__ ('alias', 'jq', '$')
__pragma__ ('noalias', 'clear')
# For use by eval'ed turtle applet
import turtle
import random
import math
def clear ():
editor.setValue ('')
turtle.reset ()
run ()
def run ():
def success (result):
global random
turtle.reset ()
rnd = random
eval (result)
random = rnd
def fail (a, b, c):
print ('Run error:', a, b, c)
# N.B. The request has to be explicitly encoded, but the response is already implicitly decoded
jq.ajax ({
'url':'http://www.transcrypt.org/compile',
'type': 'POST',
'data': JSON.stringify (editor.getValue ()),
'dataType': 'json',
'contentType': 'application/json',
'success': success,
'fail': fail
})
def mail ():
def success (result):
print (result)
def fail (a, b, c):
print ('Run error:', a, b, c)
jq.ajax ({
'url':'http://www.transcrypt.org/mail',
'type': 'POST',
'data': JSON.stringify ([document.getElementById ('mail_address') .value, editor.getValue ()]),
'dataType': 'json',
'contentType': 'application/json',
'success': success,
'fail': fail
})
def selectExample ():
def success (result):
editor.setValue (result [0])
turtle.reset () # Using old paths
window.terminate = True
console.log (result [1])
eval (result [1]) # Using new paths (so cannot clear old result)
def fail (a, b, c):
print ('Select example error:', a, b, c)
selector = document.getElementById ('select_example')
jq.ajax ({
'url':'http://www.transcrypt.org/example',
'type': 'POST',
'data': JSON.stringify (selector.options [selector.selectedIndex] .value),
'dataType': 'json',
'contentType': 'application/json',
'success': success,
'fail': fail
})
selectExample ()
这是在以下位置完成的:
http://www.transcrypt.org/live/turtle_site/turtle_site.html
[编辑]
(回应OP的评论)
实际上任何普通的 JavaScript 对象都可以通过这种方式实例化。请注意,在特殊情况下,您始终可以插入一段文字 JS 代码,如下所述:
http://www.transcrypt.org/docs/html/special_facilities.html#inserting-literal-javascript-pragma-js-and-include
对于可用的库,Transcrypt 旨在直接使用任何 JS 库,因为 JS 库往往专注于与客户端/浏览器相关的功能。
尽管如此,可用标准库的数量仍在增长。目前可用的有:
- 数学
- 日期时间
- 检查
- 迭代工具
- 日志记录
- 数学
- 随机(部分)
- 重新(几乎完成)
- 时间
- 乌龟(几乎完成)
- 警告
除此之外,还有一个小而有用的 Numpy 部分的端口,如下所述:
http://www.transcrypt.org/numscrypt/docs/html/supported_constructs.html
可在:
https://github.com/QQuick/Numscrypt