网络上也有人写了关于Delphi与Javascript的文章,其大多数使用ScriptControl等,均无法达到与Delphi自身融合的效果。我也是在翻阅自己的组件库的时候发现了这个以前收集来的代码。这个主要是使用了Mozilla的Javascript引擎,所以在程序运行的时候必须带上js3215R.dll和msvcr70.dll这两个动态链接库。
现在我们来看一看几个例子:
例程1:
说明:该例程主要是把Javascript代码以字符串的形式内置在Delphi程序代码内,然后与Delphi交互的。
unit Form;
{$I delphi.inc}
interface
uses
Windows, Messages, SysUtils, {$IFDEF D6OR7}Variants, {$ENDIF}Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, jsintf;
type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
procedure Button1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FEngine: TJSEngine;
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
FEngine := TJSEngine.Create(40000);
FEngine.StartDebugger;
FEngine.Global.AddNativeObject(Edit1, 'edit');
FEngine.Global.AddNativeObject(Button1, 'button');
FEngine.Global.Evaluate('function toggle() { ' +
' edit.Visible = ! edit.Visible;' + // Toggle the visible property on/off
' button.Caption = (edit.Visible ? "Hide" : "Show");' + // Change button
'}');
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FEngine.Free;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
FEngine.Global.Evaluate('toggle()');
end;
end.
------------------------------------------------------------------------------------------------------
例程2:
说明:就是在例程的基础上把Javascript代码放置于Delphi程序外。
unit Form;
{$I delphi.inc}
interface
uses
Windows, Messages, SysUtils, {$IFDEF D6OR7}Variants, {$ENDIF}Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, jsintf;
type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
FEngine: TJSEngine;
FScript: TJSScript;
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
FEngine := TJSEngine.Create(40000);
FScript := TJSScript.Create;
FEngine.Global.AddNativeObject(Edit1, 'edit');
FEngine.Global.AddNativeObject(Button1, 'button');
FScript.LoadRaw('script.js'); // Load the javascript code from file
FScript.Execute(FEngine); // Register the function with the JS engine
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FEngine.Free;
FScript.Free;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
FEngine.Global.Evaluate('toggle()');
end;
end.
Javascript代码如下:
function toggle() {
edit.Visible = ! edit.Visible; // Toggle the visible property on/off
button.Caption = (edit.Visible ? "Hide" : "Show"); // Change button
}
本来还有一个例程我也就不贴了,最后把所有的代码一并打包提供下载,祝大家Enjoy Youself! 点击下载此文件(2.07 MB)
http://www.lsworks.net/article/56.html