开发者

Retrieving a multiple select with GET

I implemented a javascript function which retrieves the variables sent via a GET form. However, I have several multiple select drop downs and when using GET, every option selected is sent as a different parameter. Consider the following multiple select:

               <select multiple="multiple" name="currencies">
                  <option id="option1" value="option1">Option 1</option>
               开发者_如何学运维   <option id="option1" value="option2">Option 2</option>
                  <option id="option3" value="option3">Option 3</option>
                </select>

When I select two or all of these items, this is the GET URL:

http://example.com/mypage.html?currencies=option1&currencies=option2

Hence, the javascript function only gets the first option as it splits the string when a & is encountered, which is needed when another element is found.

Is there a way around this? I would need the GET url to be something like this preferably:

http://example.com/mypage.html?currencies=option1,option2

This is the JS function using JQuery:

<script>
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 

}
</script>


The function just needs to be smart enough to spot duplicates and handle them appropriately.

For example:

var QueryString = function () {
  // This function is anonymous, is executed immediately and 
  // the return value is assigned to QueryString!
  var query_string = {};
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
                // If first entry with this name
    if (typeof query_string[pair[0]] === "undefined") {
      query_string[pair[0]] = pair[1];
                // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [ query_string[pair[0]], pair[1] ];
      query_string[pair[0]] = arr;
                // If third or later entry with this name
    } else {
      query_string[pair[0]].push(pair[1]);
    }
  } 
        return query_string;
} ();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜