本例測試效果圖:
圖片看不清楚?請點擊這裡查看原圖(大圖)。
代碼文件:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
Edit1: TEdit;
Button1: TButton;
procedure Button1Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses MsXML, SuperObject;
//這是將字符串轉換成 UTF 編碼的函數, 這裡用於 Google 的搜索地址
function ToUTF8Encode(str: string): string;
var
b: Byte;
begin
for b in BytesOf(UTF8Encode(str)) do
Result := Format('%s%s%.2x', [Result, '%', b]);
end;
//這是給 ISuperObject 准備的方法
procedure Proc(const This, Params: ISuperObject; var Result: ISuperObject);
var
jo: ISuperObject;
begin
Form1.Memo1.Clear;
for jo in Params['responseData.results'] do with Form1.Memo1.Lines do
begin
Add(jo.Format('%titleNoFormatting%:'));
Add(jo.Format('%unescapedUrl%'));
Add(EmptyStr);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
const
u = 'http://www.google.cn/uds/GwebSearch?callback=response&rsz=large&v=1.0&q=';
var
jo: ISuperObject;
req: IXMLHTTPRequest;
url: WideString;
begin
jo := SO;
jo.M['response'] := @Proc; {搜索結果將是類似 response(...) 函數格式的字符串}
url := u + ToUTF8Encode(Edit1.Text); {准備搜索地址}
//搜索
req := CoXMLHTTP.Create;
req.open('Get', url, False, EmptyParam, EmptyParam);
req.send(EmptyParam);
//搜索結果在 req.responseText(後付其全部內容), 下面語句將調用上面的 Proc 過程.
jo[req.responseText]; {這是在本系列"方法"一節用到的第二種調用方法}
end;
end.
窗體文件:
object Form1: TForm1
Left = 0
Top = 0
Caption = 'Form1'
ClIEntHeight = 358
ClIEntWidth = 547
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object Memo1: TMemo
Left = 0
Top = 0
Width = 412
Height = 358
Align = alLeft
Lines.Strings = (
'Memo1')
ScrollBars = ssBoth
TabOrder = 0
ExplicitHeight = 346
end
object Button1: TButton
Left = 440
Top = 72
Width = 75
Height = 25
Caption = 'Button1'
TabOrder = 1
OnClick = Button1Click
end
object Edit1: TEdit
Left = 418
Top = 24
Width = 121
Height = 21
TabOrder = 2
Text = 'Delphi'
end
end
下面是我以 "Delphi" 為關鍵字搜索返回的 responseText, 可以做個搜索工具了:
[Ctrl+A 全部選擇 提示:你可先修改部分代碼,再按運行]