转至内容

编码烹饪书/更改查询参数

摘自维基文库,开放世界的开放书籍

更改 URL 查询字符串中的参数(例如“param1=foo&param2=bar”)。

VBScript 解决方案

[编辑 | 编辑源码]
function ChangeQueryParameter (Query, Parameter, Value)
  
  dim sTemp
  dim SubstringStart ' Starting position of Parameter within Query
  dim SubstringEnd   ' Ending position of Parameter within Query
  
  if (Query = "") then
    ChangeQueryParameter = ""
  else
    sTemp = "&" & Query
    ' Let every parameter start with '&'

    SubstringStart = InStr (LCase(sTemp), "&" & LCase(Parameter) & "=")
    if (SubstringStart = 0) then
      ' Parameter was not yet included
      ChangeQueryParameter = sTemp
    else
      ' Parameter already existed
      ChangeQueryParameter = Left (sTemp, SubstringStart-1)    
      SubstringEnd = InStr (SubstringStart+1, sTemp, "&")
      if not (SubstringEnd = 0) then
        ' Parameter was not last in query
        ChangeQueryParameter = ChangeQueryParameter & Mid(sTemp, SubstringEnd)
        end if
      end if
    end if

  if not (Value = "") then _
    ChangeQueryParameter = ChangeQueryParameter & "&" & Parameter & "=" & Value
    ' If an empty value has been giving, the parameter will be removed

  if not (ChangeQueryParameter = "") then _
    ChangeQueryParameter = Mid(ChangeQueryParameter, 2)

  end function

strQuery = "param1=foo&param2=bar"
strQuery = ChangeQueryParameter( strQuery, "param1", "foobar" )
  ' Result: "param1=foobar&param2=bar"
strQuery = ChangeQueryParameter( strQuery, "param1", "" )
  ' Result: "param2=bar"
华夏公益教科书