我只有很少的JavaScript知识编码一个小的API站点完全客户端。
我将如何在传输密码中使用XMLHttpRequest()?或者我应该使用URLlib还是其他什么的?
它是否像在JS中那样简单:创建一个新的XMLHttpRequest对象,然后发送数据或检索一个页面?
XHR = XMLHttpRequest()
XHR.open("POST", "https://example.com/cors.php")发布于 2018-03-01 10:10:46
实际上,它与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 i一个真正的Python类(它现在是一个JS函数),但是没有必要。
看见
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 ()它是这样做的:
site.html
编辑
(回应“任择议定书”的评论)
实际上,任何普通的JavaScript对象都可以这样实例化。注意,在特殊情况下,您总是可以插入一段文字JS代码,如下所述:
facilities.html#inserting-literal-javascript-pragma-js-and-include
对于可用的lib,Transcrypt被设计成直接使用任何JS,因为JS库倾向于关注与客户机/浏览器相关的功能。
尽管如此,可用标准库的数量仍在增加。目前可获得的有:
除此之外,在Numpy中还有一个很小但很有用的港口,如以下所述:
constructs.html
可在以下网址查阅:
https://stackoverflow.com/questions/49042487
复制相似问题