На главную страницу
Форум txt.version   




Статья :: Building Dynamic Requests

Part II: Building Dynamic Requests

It is assumed that the readers of this article will be able to pass information/variables from the Flash movie to the Script, the method of which they are passed does not matter (ie Get, Post, attach to end of query string) - as long as they get their.  This is accomplished with the LoadVariables Actionscript function. 

Once the script is called it begins the process as follows: Builds the request variables.  Puts the variables into the correct format.  Builds the request Method (either GET or POST).  Opens a connection to the external source and sends the request.  Awaits the return of Information from the request.  Then formats the data and prints it out to the page - which is then returned to the Flash movie.  This is building a Form without a Form. 

The below script is the basis for the above process.  The script was written in PHP - the procedure should be the same for all scripting languages however.  As an example we will open up a connection to Yahoo - but keep in mind that this can be any URL.  Also note that the 3 variables we are sending to it - can be any variables.  The Line by Line comments below the script will better help you understand what this is doing.

1)  <?php
2)  $FormURL    = "http://search.yahoo.com/search";
3)  $FormMethod = "GET";   // You can specify either GET or POST on this line.

4)  $FormData['p']	= $SearchTerm;  //SearchTerm would be a variable sent from the Flash movie.
5)  $FormData['o']	= '1'; 
6)  $FormData['n']	= $numResult;  //numResults would also be a variable sent from the Flash movie
			      //numResults would be assigned to the a variable called n - for example.

7)  $QueryString = "";

8)  foreach ($FormData as $name => $value) {
9)     	if (strlen($QueryString) > 0)
10)      		$QueryString .= '&';
11)    		$QueryString .= $name.'='.urlencode($value);
12)  } 

13)  $url         = parse_url($FormURL);
14)  $request     = $FormMethod." ";

15)  switch ($FormMethod) {
16)   	case 'GET': 
17)      	       $request .= $url['path']."?".$QueryString." HTTP/1.1\r\n".
18)             "Host: ".$url['host']."\r\n\r\n";
19)      	       break;

20)    	case 'POST': 
21)      	       $request .= $url['path']." HTTP/1.1\r\n".
22)             "Host: ".$url['host']."\r\n".
23)             "Content-type: application/x-www-form-urlencoded\r\n".
24)             "Content-length: ".strlen($QueryString)."\r\n\r\n".
25)             $QueryString;
26)      	       break;

27)   	default:
28)      		die("Must specify a form method");
29)  }

30)  $fp = fsockopen($url['host'], 80, $err_num, $err_msg, 30);

   	// Submit form data
31)   	fputs($fp, $request);

   	// Get the response 
32)   	while (!feof($fp)) 
33)      		$response .= fgets($fp, 1024);
34)   	fclose($fp);
35)  Print "Results=$response";

Line 1:  Starts off the script.

Line 2:  Indicates which URL to request.

Line 3:  Tells the script what request method to use - either "GET" or "POST".

Lines 4-6:  These are variable/value combinations that you will be sending.  You can either specify these in the script or send them from the Flash movie.  As an example for this case - the variable 'SearchTerm' is sent from the Flash movie and assigned to a variable called 'o' which Yahoo bases the query on.  These however can be any variable/value combo.  Their is no real limit on how many of these you can have.  Their will be a limit on the amount of data they contain if your sending a request via "GET" but in almost all case's you'll never reach that limit.  

Lines 8-12:  Builds the Query String that you will be sending.

Line 13: Parse's the URL and returns it's individual parts or components.

Line 14: Starts to build the request.

Lines 15-29:  This is a switch statement (much like and If/then statement).  If the request method is "GET" it will build a request using the "GET" method.  If the request is "POST" it will build the request using the "POST" method.  This is determined by what you specify in Line 3.  Building the request method in this way simulates (exactly) what it would look like if you where to use a Form to submit this same data.  This form however does not require any user interaction - and can technically be run at any time.

Line 30:  The fsockopen function opens a socket connection to the URL we specified in line 2 of the script.  It then assigns this info to a file pointer ($fp).  This is then used in the next couple of lines.

Line 31:  The next line uses the fputs function, this submits the request that we built in lines 15-29 to the connection we opened in line 30.

Lines 32-34: After we submit the request - the page will send back the results.  These lines read in those results Line by Line and assign them to the variable $response.

Line 35:  This will print out all of the data contained in the $response variable to the page.  In this case - The results of this script would look exactly like what the web page who's URL we entered in on line 2 - Except on our server. As I mentioned earlier most of the time this data will come back as HTML (since most websites do not go out of their way to create a format that can easily be read by flash) - The hard part is formatting and parsing that data so that Flash can display it.  

If you had a Dynamic text area called 'Results' in your flash movie - and you used LoadVariables to call this script - then the dynamic Text area called 'Results' would contain all the text data contained in the $response.

Wow that was sort of confusing.  If you start playing around with the script and sending query's to different URL's it will become easier to see how to retrieve the Info back to the Flash movie. If you have any questions on this script you can ask them Here.

Building Dynamic Requests

страницы в данном разделе 
 get yahoo proxy  Имитация каталогов
 Имитация файлов и директорий. Часть 2  Building Dynamic Requests
 Виртуальный магазин?  Параллельное выполнение скриптов
 Это программа отсылает сообщение на Асю.  Передача из скрипта методом POST
 Пример работы с сессиями.  СЕССИИ - обучение и /правильное/ использование
 Как вытащить слова из текста?  Защита от двойного сабмита
 Как вырезать со страницы все ссылки?   


Разделы
Околокомпьютерная литература (375)
Программирование (102)
Программы (75)
ОС и Сети (49)
Интернет (29)
Аппаратное обеспечение (16)
Базы данных (6)
Flutter
React Native
Xamarin

Содержание сайта (выборка)
Apache
Протоколы TCP/IP (принципы, протоколы и архитектура)

PHP, PELR, JSP
PHP
JavaServer Pages (JSP)

Базы данных
Основы mysql
СУБД INFORMIX
СУБД POSTGRES
Основы проектирования реляционных баз данных

HTML, javascript
Спецификация HTML 4.01
Каскадные Таблицы Стилей, Уровень 2
Клиентский JavaScript. Справочник.
JavaScript руководство пользователя
Серверный JavaScript 1.4. Руководство по Использованию.

Паскаль, C, C++, C#
GCC (примеры)
FAQ Валентинa Озеровa DELPHI
C





 
©  programming-lang.com  справочник программиста
©  http://ekb.programming-lang.com/tlg/  бесплатный телеграм бот
©  http://ekb.programming-lang.com/tlg/  бесплатный телеграм бот
React Native
demo forum