在Delphi VCL应用程序中动态生成的HTML页面中添加对javascript文件的引用

Add reference to javascript file in dynamicaly generated HTML page in Delphi VCL application

本文关键字:添加 javascript 引用 文件 HTML Delphi 应用程序 动态 VCL      更新时间:2023-09-26

我正在制作一个Delphi XE5 VCL表单应用程序,主表单上有一个TIdHTTPServer, IdHTTPServer程序的CommandGet:

procedure TForm1.IdHTTPServerCommandGet(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var responce: TStringList;
begin
if pos('someString', ARequestInfo.UnparsedParams) > 0 then
   begin
      responce:= TStringList.Create;
      try
         responce.Add('<html>');
         responce.Add('<head>');
         responce.Add('<title>Index</title>');
         responce.Add('<script src="E:'ProjectFolder'script.js"></script>')
         responce.Add('</head>');
         // HTML content
         responce.Add('</html>');
         AResponseInfo.ContentText := responce.Text;
      finally
         responce.Free;
      end;
  end;
end;

当我更改项目的目录时,.js文件在浏览器中不可见。我的问题是如何设置对.js文件的引用,使其在我更改项目目录时可用。

传统的HTML路径是Posix格式的(即/project/scripts/scripts.js)。也要避免驱动器号。创建一个名为scripts的子文件夹,将JS文件放入其中然后引用脚本

最直接的解决方案是将脚本包含在html:

var
  scriptContent: TStringList;
...
responce.Add('<script type="text/javascript">');
scriptContent := TStringList.Create;
try
  scriptContent.LoadFromFile('<name of the script file>');
  responce.AddStrings(scriptContent);
finally
  scriptContent.Free;
end;
responce.Add('</script>');