Javascript: Parsing URL parameters


Ich habe das vor kurzem mal gebraucht und aus den zahlreichen verfügbaren Varianten eine gewählt:

// Parse url params
function parse_query_string(query) {
  var vars = query.split("&");
  var query_string = {};
  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]] = decodeURIComponent(pair[1]);
      // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [query_string[pair[0]], decodeURIComponent(pair[1])];
      query_string[pair[0]] = arr;
      // If third or later entry with this name
    } else {
      query_string[pair[0]].push(decodeURIComponent(pair[1]));
    }
  }
  return query_string;
}


// Parse the url param and do some stuff!!
function processCategoryId()
{
    var query = window.location.search.substring(1);
    var qs = parse_query_string(query);

    // If Param "CategoryID" is undefined return!
    if ((qs.CategoryId === undefined) || (qs.CategoryId.length === 0)) {
        //console.log("CategoryId undefined");
        return;
    }
    var categoryId = qs.CategoryId;
    console.log("CategoryId is defined: " + categoryId);

    // Do some stuff ;-)
    ....
}

Source: https://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-get-parameters

,

Schreibe einen Kommentar Antworten abbrechen