JSON 之 SuperObject(15): 实例 - 模拟 Google 搜索


本例测试效果图:

JSON 之 SuperObject(15): 实例 - 模拟 Google 搜索

代码文件:

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, 可以做个搜索工具了:


你可能感兴趣的:(Google)