简体   繁体   中英

How to send an HTTP request to a PHP page and get the echo'd response in AS3?

what I want to do is send an HTTP request to a PHP page, get what is being echo'd and return it.

So something like this

PHP Page:

<?php
echo "test";

The AS3 Code:

function openRequest(url) {
      open_page (url);
      return response_from_page;
}

So I can use the function in something like this in AS3

if (openRequest(php_page.php) == "test") {
   //do
}

How can I do this?

I hope I managed to explain the concept.

Thanks.

As akmozo said in a comment you can use URLLoader to perform the HTTP request and read the response after the COMPLETE event.

However, you can't do this exactly the way you say. ActionScript cannot wait for an asynchronous action (like an HTTP request) before continuing execution, so a function cannot wait before returning a value. In other words openRequest can open the HTTP request, but it cannot wait for the response before returning and exiting the function.

Instead, you can use callbacks to sequence your code:

function openRequest(url:String, then:Function):void {
    var urlLoader:URLLoader = new URLLoader();
    urlLoader.addEventListener(Event.COMPLETE, complete);
    urlLoader.loader(new URLRequest(url));
    function complete(e:Event):void {
        urlLoader.removeEventListener(Event.COMPLETE, complete); // cleanup
        then(urlLoader.data);
    }
}

Now you can write your code like this:

openRequest("php_page.php", function(response) {
    if (response === "test") {
        // do something
    }
});

Note that any code after openRequest will get executed immediately, not after the response is received. Anything you want to happen after the response is received must be placed inside the callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM