Search code examples
pythonxmlhttprequesttranscrypt

Using XMLHttpRequest() in Transcrypt


I only have minimal JavaScript knowledge from coding a small API site entirely client-side.

How would I use XMLHttpRequest() in Transcrypt? Or should I be using URLlib or something else?

Is it as simple as creating a new XMLHttpRequest object and then sending the data or retrieving a page as in JS?

XHR = XMLHttpRequest()
XHR.open("POST", "https://example.com/cors.php")

Solution

  • It's indeed just as simple as in JS, only with Python syntax:

    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)
    

    In your example that would be:

    XHR = __new__ (XMLHttpRequest())
    XHR.open("POST", "https://example.com/cors.php")
    

    Note the __new__ () function. In JavaScript it would have been the new operator but Python syntax doesn't allow that.

    If you want to avoid __new__ () altogether you may encapsulate XMLHttpRequest i a true Python class (it's a JS function now), but there's no need to.

    See

    http://www.transcrypt.org/docs/html/special_facilities.html#creating-javascript-objects-with-new-constructor-call

    for a general explantion on using or avoiding __new__ ().

    You may also go via JQuery as in the following somewhat bigger example:

    __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 ()
    

    This is the way it's done at:

    http://www.transcrypt.org/live/turtle_site/turtle_site.html

    [EDIT]

    (in response to comment of OP)

    Indeed any ordinary JavaScript object can instantiated this way. Note that in special cases you can always interject a piece of literal JS code, as described in:

    http://www.transcrypt.org/docs/html/special_facilities.html#inserting-literal-javascript-pragma-js-and-include

    As for the available libs, Transcrypt is designed to use any JS lib directly, since JS libs tend to be focused on functionality that is relevant to the client/browser.

    Nevertheless the number of available standard libs is growing. Currently available are:

    • cmath
    • datetime
    • inspect
    • itertools
    • logging
    • math
    • random (partially)
    • re (almost complete)
    • time
    • turtle (almost complete)
    • warnings

    Apart from that there's a port of a small but useful part of Numpy as described in:

    http://www.transcrypt.org/numscrypt/docs/html/supported_constructs.html

    It is available at:

    https://github.com/QQuick/Numscrypt