You're right that it has to do with async execution - the fetch happens in the background, and you can't just check req.status right away - you need to register an event listener (I think you were probably just lucky in your tests that the requests returned very quickly :-) ). (Update: Oops, see replies!) See e.g. Using XMLHttpRequest.

The secondAnother issue to be aware of is that scripts in the "democode" page are run in a perl that gets ended when the main script is done; no async stuff is possible. For that, you need to either embed <script> tags in an HTML file, or use the "Run & Persist" mode of the "mini IDE". In the latter, the following works for me. (Note there are also other events on XMLHttpRequest, such as error and abort.

use warnings; use 5.028; use WebPerl qw/js js_new/; my $xhr = js_new('XMLHttpRequest'); $xhr->addEventListener("load", sub { say "Loaded! <<<<<",$xhr->{responseText},">>>>>\n"; }); $xhr->open("GET", "http://localhost:5000/"); say "Sending...\n"; $xhr->send();

Actually, I am currently working on a subclass of Future::HTTP that I'd like to include by default in WebPerl to make HTTP requests easier out of the box, hopefully I can release it soon.


In reply to Re: webperl: fetching data over the web by haukex
in thread webperl: fetching data over the web by LanX

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.