开发者

Access array of posted html form variables with same name[]

I am working on a web application written in delphi and am having trouble getting the values from an array of values. The form looks similar to this:

<form method="post">
  <input type="hidden" name="keyword[]" value="1"/>
  <input type="hidden" name="keyword[]" value="2"/>
  <input type="hidden" name="keyword[]" value="3"/>
  <input type="submit" value="submit"/>
</form>

If this were a single input with a unique name, I could pull the data using this:

var cKeyword : String ;
cKeywo开发者_运维百科rd := Request.ContentFields.Values['keyword'] ;

I'm looking for something like this:

var aKeywords : Array of String ;
aKeywords := Request.ContentFields.Values['keyword[]'] ;

In PHP you could just use $aKeywords = $_POST['keyword'], I'm hoping there's a way to do this in delphi.

Thanks in advance for any help you can provide.


The ContentFields property is just an ordinary TStrings object, so its Values property always returns a string. When an HTML form has multiple successful controls with the same name, they're simply all returned, one after the next. That means the TStrings object will have multiple entries with the same Names value. You'll need to iterate over all the entries to find the ones with matching names.

Here's a function that might help.

function GetArrayFieldValues(ContentFields: TStrings; const FieldName: string): TStringDynArray;
var
  i: Integer;
  Values: TStrings;
begin
  Values := TStringList.Create;
  try
    for i := 0 to Pred(ContentFields.Count) do
      if ContentFields.Names[i] = FieldName then
        Values.Add(ContentFields.ValueFromIndex(i));
    Result := Values.ToStringArray;
  finally
    Values.Free;
  end;
end;

Call it like this:

aKeywords := GetArrayFieldValues(Request.ContentFields, 'keyword[]');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜