Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "Начинающим";
Текущий архив: 2011.04.10;
Скачать: [xml.tar.bz2];

Вниз

HTML   Найти похожие ветки 

 
student22 ©   (2011-01-13 16:02) [0]

Подскажите как делать правильнее:

формировать ответ клиенту в виде HTML-страницы приямо внутри приложения делфи, к примеру:

AResponseInfo.ContentText:="<html>"+

                           "<h1 align="center"> Время сервера EditTime.Text +
                           
                            "</h1><br>"+  "</html>";

или же надо отдельно создавать HTML-файл, тянуть в него данные из приложения и только потом отправлять клиенту?


 
sniknik ©   (2011-01-13 16:11) [1]

не скажу насчет правильности, а проще использовать TPageProducer, в котором можно хранить хоть весь html и менять только динамические части.


 
sniknik ©   (2011-01-13 16:12) [2]

> создавать HTML-файл, тянуть в него данные
можно и так, причем с TPageProducer логика практически не меняется, просто указываешь нужный файл.


 
student22 ©   (2011-01-13 16:30) [3]

спасибо
> sniknik ©


 
12 ©   (2011-01-13 16:36) [4]

проще использовать TPageProducer
+1

самостоятельно додумался так(как то давно делал)
в бд в txt-поле HTML-файлы с метками
аля
<html><h1 align="center"> Время сервера @MyTagTime@ </h1><br></html>

а потом
Response := StringReplace(q.FieldBynaem().asstring,"@MyTagTime@", Value)


 
Дмитрий Белькевич   (2011-01-13 17:07) [5]


> или же надо отдельно создавать HTML-файл, тянуть в него
> данные из приложения и только потом отправлять клиенту?


Как угодно. Как сделаешь - так и будет работать. Но с TPageProducer, думаю, удобнее. Мы у себя TDataSetPageProducer пользуем, хотя он кроме прицепленного датасета и обвязки ничем не отличается от TPageProducer.


 
Ega23 ©   (2011-01-13 17:16) [6]

Лучше формировать JSON


 
sniknik ©   (2011-01-13 17:26) [7]

json это для активной странички с ajax, а так кто его примет и обработает без него? ну если к примеру get запрос на старте от браузера страницы index.html?


 
Дмитрий Белькевич   (2011-01-13 18:12) [8]


> Лучше формировать JSON


JSON - для активных страниц, парсить json ответы на стороне клиента некому, боюсь, да и запрашивать.

Для простых реализаций - get достаточно, незачем в ajax лезть. Хотя активное прикольно смотрится.


 
Дмитрий Белькевич   (2011-01-13 18:13) [9]

Хотя, в общем-то и ajax через get работает, насколько я помню. Ну - только параметры запроса/ответа хитрые.


 
Ega23 ©   (2011-01-13 18:20) [10]


> Хотя, в общем-то и ajax через get работает, насколько я
> помню.


И get и post


 
student22 ©   (2011-01-13 18:45) [11]

подскажите в чем дело, добавил на форму TPageProducer, указал путь к html-файлу, в обработчике прописал:

procedure TfrmMain.PageProducer2HTMLTag(Sender: TObject; Tag: TTag;
 const TagString: string; TagParams: TStrings; var ReplaceText: string);
begin
  case tag of
     tgCustom: if TagString = "Time1" then ReplaceText := EditTime.Text;
  end;
end;

html-файл:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
<title> Server Time  </title>
</head>

<body>

<H3> Время сервера: <#Time1> </H3>  

</body>
</html>

В браузере отображается строчка:

Время сервера: <#Time1>

Не могу разобраться почему


 
Anatoly Podgoretsky ©   (2011-01-13 18:47) [12]

http://podgoretsky.com/Redir.aspx?id=140&DownloadFile=~/ftp/Docs/Delphi/Podgoretsky/drbobinetrus.doc


 
student22 ©   (2011-01-13 19:01) [13]

ну там же про TPageProducer упомянто в двух местах и все


 
sniknik ©   (2011-01-13 19:44) [14]

> Не могу разобраться почему
а отладчика у тебя совсем совсем нету? бедненький.


 
Медвежонок Пятачок ©   (2011-01-13 20:24) [15]

заниматься пейджпродусером и тратить на него время было оправдано в 19 столетии. но сегодня уже 21 век.


 
student22 ©   (2011-01-13 21:37) [16]

событие у  TPageProducer  onHTMLTag вообще не срабатывает!!! везде приведены примеры где  TPageProducer используется нв веб-форме, у меня же веб-сервер с IdHTTPServer, в этом может быть причина?


 
sniknik ©   (2011-01-13 21:51) [17]

> с IdHTTPServer, в этом может быть причина?
именно в этом! + фон рабочего стола розового цвета, это всегда дает нерабочую комбинацию... а код использования ну совершенно не причем.

продолжай в том же духе, вали сессию.


 
student22 ©   (2011-01-13 21:53) [18]

а если серьезно


 
sniknik ©   (2011-01-13 22:43) [19]

серьезней некуда, нет кода = не о чем говорить.


 
student22 ©   (2011-01-13 23:01) [20]

procedure TfrmMain.PageProducer1HTMLTag(Sender: TObject; Tag: TTag;
 const TagString: string; TagParams: TStrings; var ReplaceText: string);
begin
case Tag of
tgCustom: if TagString = "Name" then ReplaceText := "Partner";
end;


 
sniknik ©   (2011-01-13 23:04) [21]

ну, как хочешь. партизань дальше.


 
student22 ©   (2011-01-13 23:19) [22]

да ничего я ни партизаню, дело было так:

Я нашел пример веб-сервера на indy (idhttpserver). И пытаюсь понять как формировать html-страницы для клиента в зависимости от того что клиент просит. Например хочу станицу ту или ту, а я пока научился только формировать ответ серверу вот так:

AResponseInfo.ContentText:="<html>"+ "<h1 align="center"> Время сервера "+ EditTime.Text +  "</h1>

А мне надо вот например как в WebBroker, по параметрам в адресной строке сервер видит, что именно хочет клиент и отдает нужную информацию. Т.е. например клиент запросил значение переменной такой-то и сервер ему его показал, т.е. как динамически формировать страницы.

Вот последние часа 4 я и пытаюсь начится это делать, правда плохо получается.


 
student22 ©   (2011-01-13 23:20) [23]


> Я нашел пример веб-сервера на indy (idhttpserver). И пытаюсь
> понять как формировать html-страницы для клиента в зависимости
> от того что клиент просит. Например хочу станицу ту или
> ту, а я пока научился только формировать ответ КЛИЕНТУ вот
> так:


 
sniknik ©   (2011-01-14 00:02) [24]

> а я пока научился только формировать ответ серверу вот так:
> AResponseInfo.ContentText:="<html>"+ "<h1 align="center"> Время сервера "+ EditTime.Text +  "</h1>
а как у тебя НЕ ПОЛУЧАЕТСЯ формировать этот ответ с помощью PageProducer? или ты рассчитываешь на чудо, типа положил компоненту и она за тебя думает в какой момент, и что тебе нужно будет передавать. так что ли?

> вот например как в WebBroker, по параметрам в адресной строке
и где хотя бы попытка разбора/обработки этих самых параметров?

p.s. никому не интересно как ты умеешь, если обсуждение идет о том как не умеешь.


 
student22 ©   (2011-01-14 00:07) [25]


> и где хотя бы попытка разбора/обработки этих самых параметров?


Дак вот я пытаюсь выяснить как отвечать клиенту  именно на то, что он просит, а не просто формировать в ответ сраницу


 
Германн ©   (2011-01-14 00:47) [26]


> Дак вот я пытаюсь выяснить как отвечать клиенту

Так тебя спрашивают как именно пытаешься? Но ответ ждут не в виде общих слов, а в виде того кода, который ты пишешь. И желательно получить код в размере, достаточном для его воспроизведения на компьютере отвечающего. Иначе никак тебе не помочь!


 
student22 ©   (2011-01-14 08:28) [27]

unit MainForm;

interface

uses
 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
 IdBaseComponent, IdComponent, IdTCPServer, IdContext, StdCtrls, IdScheduler,
 IdSchedulerOfThread, IdSchedulerOfThreadDefault, CheckLst, ComCtrls, ExtCtrls,
 IdDsnCoreResourceStrings, IdStack, IdSocketHandle, ShellAPI, IdGlobal,
 IniFiles, IdAntiFreezeBase, IdAntiFreeze, IdCustomTCPServer, IdStackWindows,
 IdCustomHTTPServer, IdHTTPServer, HTTPApp, HTTPProd;

type
 TfrmMain = class(TForm)
   pnlButtonBar: TPanel;
   pcMain: TPageControl;
   tsSettings: TTabSheet;
   Label2: TLabel;
   Label3: TLabel;
   Label4: TLabel;
   lbIPs: TCheckListBox;
   cbPorts: TComboBox;
   edPort: TEdit;
   tsProcessLog: TTabSheet;
   lbProcesses: TListBox;
   btnStartStop: TButton;
   IdAntiFreeze1: TIdAntiFreeze;
   IdSchedulerOfThreadDefault1: TIdSchedulerOfThreadDefault;
   Server: TIdHTTPServer;
   Label1: TLabel;
   edServerRoot: TEdit;
   A: TEdit;
   B: TEdit;
   Timer1: TTimer;
   Label5: TLabel;
   Label6: TLabel;
   EditTime: TEdit;
   PageProducer1: TPageProducer;
   procedure btnStartStopClick(Sender: TObject);
   procedure FormCreate(Sender: TObject);
   procedure FormDestroy(Sender: TObject);
   procedure lbProcessesDrawItem(Control: TWinControl; Index: Integer;
     Rect: TRect; State: TOwnerDrawState);
   procedure ServerStatus(ASender: TObject; const AStatus: TIdStatus;
     const AStatusText: String);
   procedure ServerException(AContext: TIdContext; AException: Exception);
   procedure FormActivate(Sender: TObject);
   procedure ServerExecute(AContext: TIdContext);
   procedure ServerConnect(AContext: TIdContext);
   procedure ServerDisconnect(AContext: TIdContext);
   procedure edPortKeyPress(Sender: TObject; var Key: Char);
   procedure ServerCommandGet(AContext: TIdContext;
     ARequestInfo: TIdHTTPRequestInfo;
     AResponseInfo: TIdHTTPResponseInfo);
   procedure Timer1Timer(Sender: TObject);
   procedure PageProducer1HTMLTag(Sender: TObject; Tag: TTag;
     const TagString: string; TagParams: TStrings; var ReplaceText: string);
 private
   { Private declarations }
   function CheckStartOk : Boolean;

   function StartServer : Boolean;
   function StopServer  : Boolean;

   procedure PopulateIPAddresses;
   function PortDescription(const PortNumber: integer): string;

   procedure LoadDefaultValues;
   procedure SaveDefaultValues;

   procedure CheckOptions;
   function GetServerOnline: Boolean;

   function InternalServerBeforeStart : Boolean;
   procedure InternalServerAfterStart;

   function InternalServerBeforeStop : Boolean;
   procedure InternalServerAfterStop;

   procedure Log(Msg : String; Color : TColor = clBlack);
   procedure SetControls;
 public
   { Public declarations }
   property ServerOnline : Boolean read GetServerOnline;
 end;

var
r: string;
 frmMain : TfrmMain;
 Ini     : TIniFile;

implementation

{$R *.DFM}

procedure TfrmMain.btnStartStopClick(Sender: TObject);
begin
// This procedure should never change.
 if ServerOnline then
   StopServer
 else
   StartServer;
end;

function TfrmMain.CheckStartOk: Boolean;
var
 i, c : Integer;
begin
// This section should stay the same, add your new code below
 i := 0;
 for c := 0 to lbIPs.Items.Count -1 do
   begin
     if lbIPs.Checked[c] then
       inc(i);
   end;
 result := i > 0;
 if not result then
   begin
     Log("Can""t start server until you select at least one IP to bind to.", clRed);
     MessageDlg("Can""t start server until you select at least one IP to bind to.", mtError, [mbOK], 0);
   end;
// Add your code after this comment
end;

procedure TfrmMain.PageProducer1HTMLTag(Sender: TObject; Tag: TTag;
 const TagString: string; TagParams: TStrings; var ReplaceText: string);
begin
case Tag of
tgCustom: if TagString = "Name" then ReplaceText := "Partner";
end;
end;


procedure TfrmMain.PopulateIPAddresses;
var
 i : integer;
begin
// Again this section should not change
 with lbIPs do
   begin
     Clear;
     Items := GStack.LocalAddresses;
     Items.Insert(0, "127.0.0.1");
   end;
 try
   cbPorts.Items.Add(RSBindingAny);
   cbPorts.Items.BeginUpdate;
   for i := 0 to IdPorts.Count - 1 do
     cbPorts.Items.Add(PortDescription(Integer(IdPorts[i])));
 finally
   cbPorts.Items.EndUpdate;
 end;
end;

function TfrmMain.PortDescription(const PortNumber: integer): string;
begin
// Guess what more code that shouldn"t change
 with TIdStackWindows(GStack).WSGetServByPort(PortNumber) do
   try
     if PortNumber = 0 then
       begin
         Result := Format("%d: %s", [PortNumber, RSBindingAny]);
       end
     else
       begin
         Result := "";    {Do not Localize}
         if Count > 0 then
           begin
             Result := Format("%d: %s", [PortNumber, CommaText]);    {Do not Localize}
           end;
       end;
   finally
     Free;
   end;
end;

function TfrmMain.StartServer: Boolean;
var
 Binding : TIdSocketHandle;
 i : integer;
 SL : TStringList;
begin
// This code starts the server up and posts back information about
// the server starting up.
// You should place your pre and post startup code in InternalServerBeforeStart
// and InternalServerAfterStart accordingly.
 Result := false;
 if not CheckStartOk then
   exit;

 SL := TStringList.Create;

 if not StopServer then
   begin
     Log( "Error stopping server", clRed );
     Result := false;
     exit;
   end;

 Server.Bindings.Clear; // bindings cannot be cleared until TServer is inactive
 try
   try
     Server.DefaultPort := StrToInt(edPort.Text);
     for i := 0 to lbIPs.Items.Count - 1 do
       if lbIPs.Checked[i] then
         begin
           Binding := Server.Bindings.Add;
           Binding.IP := lbIPs.Items.Strings[i];
           Binding.Port := StrToInt( edPort.Text );
           Log( "Server bound to IP " + Binding.IP + " on port " + edPort.Text );
         end;

     if InternalServerBeforeStart then
       begin
         Server.Active := true;
         result := Server.Active;

         InternalServerAfterStart;
         if ServerOnline then
           begin
             Log( "Server started", clGreen );
             btnStartStop.Caption := "Stop Server";
             SetControls;
           end;
       end;
   except
     on E : Exception do
       begin
         Log( "Server not started", clRed );
         Log( E.Message, clRed );
         Result := false;
       end;
   end;
 finally
   FreeAndNil( SL );
 end;
end;


 
student22 ©   (2011-01-14 08:29) [28]

продолжение:

function TfrmMain.StopServer: Boolean;
var
 b : Boolean;
begin
// This code stops the server and posts back information about
// the server shutting down.
// You should place your pre and post shutdown code in InternalServerBeforeStop
// and InternalServerAfterStop accordingly.

 Result := false;

 b := Server.Active;

 if InternalServerBeforeStop then
   begin
     Server.Active := false;
     Server.Bindings.Clear;
     Result := not Server.Active;

     if result then
       begin
         if b then
           Log( "Server stopped", clGreen );
       end
     else
       begin
         Log( "Server not stopped", clRed );
       end;

     InternalServerAfterStop;
     btnStartStop.Caption := "Start Server";
     SetControls;
   end
 else
   Log( "Server not stopped", clRed );
end;

procedure TfrmMain.Timer1Timer(Sender: TObject);
begin
  EditTime.Text := TimeToStr(now);
  B.Text := IntToStr(StrToInt(B.Text)+5);
end;

procedure TfrmMain.FormCreate(Sender: TObject);
begin
// Initialization routines.  You should find the appropriate procedure
// to initialize your stuff below.  The form create should hardly ever
// need to be changed.
 Ini := TIniFile.Create(ChangeFileExt(ParamStr(0), ".ini"));
 pcMain.ActivePageIndex := 0;
 pcMain.Align  := alClient;
 PopulateIPAddresses;
 StopServer;
 LoadDefaultValues;
 CheckOptions;
end;

procedure TfrmMain.FormDestroy(Sender: TObject);
begin
// If you created anything in form create or in one of the other
// initialization routines then get rid of it here.
 StopServer;
 SaveDefaultValues;
 Ini.Free;
end;

procedure TfrmMain.LoadDefaultValues;
var
 i, c : Integer;
 s    : String;
begin
// This is were you get the chance to load values from the global
// Ini file.  The section for ports and IP"s has been added in here
// for you by default.
 edPort.Text := Ini.ReadString("Settings", "Port", edPort.Text);
 c := Ini.ReadInteger("Settings", "IPs", 0);
 for i := 1 to c do
   begin
     s := Ini.ReadString("Settings", "IP" + IntToStr(i), "");
     if lbIPs.Items.IndexOf(s) > -1 then
       lbIPs.Checked[lbIPs.Items.IndexOf(s)] := true;
   end;
 edServerRoot.Text := Ini.ReadString("Settings", "ServerRoot", ExtractFilePath(ParamStr(0)) + "Docs");
end;

procedure TfrmMain.SaveDefaultValues;
var
 i, c : Integer;
begin
// This is were you get the chance to save values to the global
// Ini file.  The section for ports and IP"s has been added in here
// for you by default.
 Ini.WriteString("Settings", "Port", edPort.Text);
 c := 0;
 for i := 0 to lbIPs.Items.Count -1 do
   if lbIPs.Checked[i] then
     begin
       inc(c);
       Ini.WriteString("Settings", "IP" + IntToStr(c), lbIPs.Items[i]);
     end;
 Ini.WriteInteger("Settings", "IPs", c);
 Ini.WriteInteger("Placement", "Top", Top);
 Ini.WriteInteger("Placement", "Left", Left);
end;

procedure TfrmMain.CheckOptions;
var
 i   : Integer;
 opt : string;
 bDoAutoStart : Boolean;

 function OptName : String;
 begin
   if pos("=", opt) > 0 then
     begin
       result := copy(opt, 1, pos("=", opt) - 1);
       if result[1] in ["-", "/", "\"] then
         result := copy(result, 2, length(result));
     end
   else
     result := opt;
 end;

 function OptValue : String;
 begin
   if pos("=", opt) > 0 then
     result := copy(opt, pos("=", opt) + 1, length(opt))
   else
     result := opt;
 end;
begin
// The check options procedure should be used to check commandline options
// if you wish to support command line options then please add it here.
// By default port and autostart are supported.
 bDoAutoStart := false;
 for i := 1 to ParamCount do
   begin
     opt := LowerCase(ParamStr(i));

     if OptName = "port" then
       edPort.Text := OptValue;

     if OptName = "autostart" then
       bDoAutoStart := true;
   end;
   
 if bDoAutoStart then
   StartServer;
end;

function TfrmMain.GetServerOnline: Boolean;
begin
// Just a faster way then checking server.active for some
 result := Server.Active;
end;


 
student22 ©   (2011-01-14 08:29) [29]

и еще продолжение:

procedure TfrmMain.lbProcessesDrawItem(Control: TWinControl;
 Index: Integer; Rect: TRect; State: TOwnerDrawState);
begin
// This draws the items in the Process Log in colors to allow quick
// visual inspection
 with Control as TListBox do
 begin
   Canvas.Brush.Color := Color;

   Canvas.FillRect(Rect);
   Canvas.Font.Color := TColor(Items.Objects[Index]);
   Canvas.TextOut(Rect.Left + 2, Rect.Top, Items[Index]);
 end;
end;

procedure TfrmMain.Log(Msg: String; Color: TColor);
begin
// Simply adds a new item to the process log and then makes it the
// currently selected item.
 lbProcesses.Items.AddObject(Msg, Pointer(Color));
 lbProcesses.ItemIndex := lbProcesses.Items.Count -1;
end;

procedure TfrmMain.ServerStatus(ASender: TObject; const AStatus: TIdStatus;
 const AStatusText: String);
begin
// Logs any ServerStatus messages to the Process Log
 Log(AStatusText);
end;

procedure TfrmMain.ServerException(AContext: TIdContext;
 AException: Exception);
begin
// Logs any server exceptions to the Process Log
 Log(AException.Message, clRed);
end;

function TfrmMain.InternalServerBeforeStart: Boolean;
begin
 // Preform your startup code here.  If you do not wish the server to start
 // then simply return false from this function and report back the proper
 // error by calling Log(YourMessage, clRed);
 result := true;
end;

procedure TfrmMain.InternalServerAfterStart;
begin
// Your code should go here.  At this point the server is active.
// So if you need to stop it then you should call StopServer
// or for a hard halt call Server.Active := false;
end;

procedure TfrmMain.InternalServerAfterStop;
begin
// Your code should go here.  At this point the server has been stoped.
// So if you need to start it then you should call StartServer
// or for a force start call Server.Active := true;
end;

function TfrmMain.InternalServerBeforeStop: Boolean;
begin
 // Preform your shutdown code here.  If you do not wish the server to stop
 // then simply return false from this function and report back the proper
 // error by calling Log(YourMessage, clRed);
 Result := true;
end;

procedure TfrmMain.SetControls;
begin
// Sets up the UI controls to either be enabled or disabled based upon
// the current server state.  See below for examples.
 lbIPs.Enabled   := not ServerOnline;
 edPort.Enabled  := not ServerOnline;
 cbPorts.Enabled := not ServerOnline;
end;

procedure TfrmMain.FormActivate(Sender: TObject);
begin
 Top := Ini.ReadInteger("Placement", "Top", Top);
 Left:= Ini.ReadInteger("Placement", "Left", Left);
end;

procedure TfrmMain.ServerExecute(AContext: TIdContext);
begin
// Your stuff for OnExecute goes here.

end;

procedure TfrmMain.ServerConnect(AContext: TIdContext);
begin
 Log("Client connection established from ip: " + AContext.Connection.Socket.Host, clBlue);
end;

procedure TfrmMain.ServerDisconnect(AContext: TIdContext);
begin
 Log("Client connection removed from ip: " + AContext.Connection.Socket.Host, clBlue);
end;

procedure TfrmMain.edPortKeyPress(Sender: TObject; var Key: Char);
begin
 if not (Key in ["0", "1".."9", #8]) then
   Key := #0;
end;

procedure TfrmMain.ServerCommandGet(AContext: TIdContext;
 ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
 rPage : String;
begin

Log("Serving: " + ARequestInfo.Document + " to " + AContext.Connection.Socket.Host, clBlue);
 if (ARequestInfo.Document <> "") and
    (ARequestInfo.Document <> "/") and
    (ARequestInfo.Document <> "\") then
   rPage := Copy(ARequestInfo.Document, 2, Length(ARequestInfo.Document))
 else
   rPage := "index.htm";
 rPage := StringReplace(rPage, "/", "\",[rfReplaceAll, rfIgnoreCase]);
 rPage := IncludeTrailingBackslash(edServerRoot.Text) + rPage;
 if FileExists(rPage) then
   AResponseInfo.ServeFile(AContext, rPage)
 else
   AResponseInfo.ContentText := "<H1>ERROR</H1>File not found: "+ARequestInfo.Document;

end;

end.

При подключении к серверу, клиент сначала получает страницу index.htm, на которой есть ссылка на страницу time.htm, на странице time.htm есть тег <#NAME>, как я понимаю при переходе со страницы index.htm на страницу time.htm сервер должен сначала заменить тег  <#NAME> на Partner и затем отправить страницу time.htm клиенту, чего не происходит и клиенту приходит страница time.htm с тегом <#NAME>.


 
sniknik ©   (2011-01-14 09:38) [30]

хуже идиота только исполнительный идиот...

вот нафига тут весь код "примера веб-сервера на indy" который ты нашел? тебя просили код, попыток использования PageProducer-а в формируемом ответе, которого в примере естественно нет.
то что ты "бахнул" компонент на форму, прописал событие и даже выделил его в данном коде, оно как бы СОВСЕМ НИЧЕГО НЕ ЗНАЧИТ, без ХОТЯ БЫ ПОПЫТОК использования этого компонента.
естественно у тебя переменная в html-е не меняется, ведь ты ее как есть в файле так и отдаешь,  в обход "продюсера".


 
student22 ©   (2011-01-14 10:18) [31]

ааааааааааааа!!!!!

я в продюсере указал путь к html-файлу, этого не достаточно, чтобы он заменил там мои теги на нужные мне данные???

вот html-файл:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
<title> Server Time  </title>
</head>

<body> <#Name>

<H3> Время сервера:  </H3>  

</body>
</html>

вот обработчик:

procedure TfrmMain.PageProducer1HTMLTag(Sender: TObject; Tag: TTag;
const TagString: string; TagParams: TStrings; var ReplaceText: string);
begin
case Tag of
tgCustom: if TagString = "Name" then ReplaceText := "Partner";
end;
end;

я думал, что продюсеру нужен только путь к файлу, а он в нем все что надо заменит(при присутствии обработчика, представленного выше) и отправит обработанный файл

подскажите, пожалуйста, что не так делаю


 
student22 ©   (2011-01-14 10:24) [32]

т.е надо формировать ответ после обработки продюсером файла?
это делается в обработчике этого же события?


 
sniknik ©   (2011-01-14 10:31) [33]

> я в продюсере указал путь к html-файлу, этого не достаточно, чтобы он заменил там мои теги на нужные мне данные???
этого (и обработчика) достаточно, с условием если его ИСПОЛЬЗОВАТЬ. вообще что угодно сбоку положи работать не будет.

> это делается в обработчике этого же события?
это делается в формировании ответа, вот тут например
> AResponseInfo.ContentText := "<H1>ERROR</H1>File not found: "+ARequestInfo.Document;


 
Дмитрий Белькевич   (2011-01-14 10:36) [34]


> я думал, что продюсеру нужен только путь к файлу, а он в
> нем все что надо заменит(при присутствии обработчика, представленного
> выше) и отправит обработанный файл


Продьюсер ничего не меняет в файле и никуда ничего не отправляет.

Читайте доки, они рулез:

"property HTMLFile public Specifies the name of a file that contains the HTML template used to generate the value returned by the Content method."


 
student22 ©   (2011-01-14 10:37) [35]

у меня при первои обращении к серверу открывается страница index.htm, по ссылке находящейся на ней я перехожу на страницу time.htm:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
<title> Server Time  </title>
</head>

<body> <#Name>

<H3> Время сервера:  </H3>  

</body>
</html>

Вот как правильно сформировать ответ в этом случае, чтобы файл time.htm обрабатывался и отправлялся клиенту при переходе по соответствующей ссылке, честно искал в интернете, но не нашел


 
Дмитрий Белькевич   (2011-01-14 10:43) [36]

Можешь еще здесь порыться, если хэлпа недостаточно:

http://google.com/codesearch?hl=ru&lr=&q=TPageProducer+lang%3Apascal&sbtn=%D0%9F%D0%BE%D0%B8%D1%81%D0%BA


 
sniknik ©   (2011-01-14 11:39) [37]

> как правильно сформировать ответ в этом случае
какой случай... он и нужен то для "обобщения" случаев ("сокрытием" разницы между файлом и текстом встроенным в прогу, а ты пытаешься "выпытать" правильность от конкретного (и ничего не значащего в логике работы) файла...

> честно искал в интернете, но не нашел
чего искать то? блин, на каждое присвоение дока должна быть? ContentText-ту без нее не можешь генерированный продюсером текст присвоить?


 
sniknik ©   (2011-01-14 11:42) [38]

> Можешь еще здесь порыться, если хэлпа недостаточно:
ага, "помощь"... в первом же открытом примере продюсер используется как хранилище/"парсер" html т.е. не по назначению. если там все примеры похожие похоже то ...


 
student22 ©   (2011-01-14 11:42) [39]

хочу просто понять  страницу  сформированную продюсером отправить клиенту


 
student22 ©   (2011-01-14 11:44) [40]


> хочу просто понять как  страницу  сформированную продюсером
> отправить клиенту


 
sniknik ©   (2011-01-14 11:47) [41]

присвой ContentText-ту.


 
student22 ©   (2011-01-14 11:58) [42]

спасибо за помощь

> sniknik ©


извиняюсь ,что весь мозг вытр....



Страницы: 1 2 вся ветка

Форум: "Начинающим";
Текущий архив: 2011.04.10;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.61 MB
Время: 0.005 c
2-1294837070
TKN
2011-01-12 15:57
2011.04.10
библиотека qtinf.dll при установке приложения


6-1233550485
vann
2009-02-02 07:54
2011.04.10
Как задать таймаут при определении имени хоста?


2-1294752413
начинающий1993
2011-01-11 16:26
2011.04.10
вызвать B из A


15-1293211137
alexdn_
2010-12-24 20:18
2011.04.10
Немножко php


2-1294913584
Finder
2011-01-13 13:13
2011.04.10
замена OleVariant





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский