4

I would like to fetch a file via transcrypt code. Usually this is done with XMLHttpRequest. In Javascript scripts the new constructor is used for this. How do I proceed in transcrypt for it? Here is my not-working code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def read_file():
    xmlhttp=XMLHttpRequest()
    xmlhttp.open('GET', "https://raw.githubusercontent.com/bunkahle/Transcrypt-Examples/master/README.md", False);
    xmlhttp.send()
    console.log(xmlhttp.responseText)

and the html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="__javascript__/read_file.js"></script>
    <title>Read File</title>
  </head>
  <body>
    <main>
        <h1>Read a file!</h1>
        <p id="p1" class="para1">Read a file!</p>
      <button id="button1" onclick="read_file.read_file()">Click for retrieving text file</button><br><br>
      <p id="demo"></p>
    </main>
  </body>
</html>
Jacques de Hooge
  • 6,750
  • 2
  • 28
  • 45
bunkus
  • 975
  • 11
  • 19

1 Answers1

2

You can use the __new__ function to create native JavaScript objects:

(Note that for instantiating Python/Transcrypt classes this isn't needed)

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def read_file():
    xmlhttp= __new__ (XMLHttpRequest())
    xmlhttp.open('GET', "https://raw.githubusercontent.com/bunkahle/Transcrypt-Examples/master/README.md", False);
    xmlhttp.send()
    console.log(xmlhttp.responseText)

More info on this can be found at:

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

Jacques de Hooge
  • 6,750
  • 2
  • 28
  • 45
  • Thanks - people who read the docs have clearly more advantages! But sometimes one tends to get results by trial and error. – bunkus Feb 18 '18 at 12:35