2

I'm curious, what is the best practice to grab any url params from the URL ?


Example

http://localhost:8080/BIM/teacher/reports/chapter-quiz/assignment?assessmentId=206a9246&classroomId=722bfadb

The goal is to grab the value of :

  • assessmentId
  • classroomId

1. Make a parseUrl function

function parseUrl(url) {
    var urlParamSplit = url.split("?");

    if (urlParamSplit.length !== 2) {
        return "InvalidUrlNoParamsSet";
    }

    var paramsList = urlParamSplit[1].split("&");
    if (paramsList.length < 1) {
        return "InvalidUrlNoParamsFound";
    }

    var paramsObj = {};
    paramsList.forEach(function(item) {
        var keyValueArray = item.split("=");
        paramsObj[keyValueArray[0]] = keyValueArray[1];
    });

    return paramsObj;
}

var params = parseUrl(href);



console.log(params.assessmentId) // 206a9246
console.log(params.classroomId) // 722bfadb

2. Grab it from hidden input

Throw this in the HTML page

<input id="assessmentId" type="hidden" value="<c:out escapeXml="true" value="${param.assessmentId}" />" />
<input id="classroomId" type="hidden" value="<c:out escapeXml="true" value="${param.classroomId}" />" />




console.log($("#assessmentId").val()) // 206a9246
console.log($("#classroomId").val())  // 722bfadb

So far, I've tried 2 approaches,they both give me the data I wanted, but I'm not sure which one, I should use.

If there's other approach that I should consider that please kindly suggest.

Community
  • 1
  • 1
code-8
  • 54,650
  • 106
  • 352
  • 604

2 Answers2

1

I think the first method is more powerful if you have several parameters to grab from the url, or if you have some parameters that generate dynamicly instead of the second method in this case (dynamic params) you have to loop and create inputs also dynamicly.

Short : use the first method if you have several parameters to grap or dynamicly generated parameter, use the second if you have less parameters (static & controlables parameters).

For more solutions/ideas this link & this one may help you.

Community
  • 1
  • 1
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
1

if the http request is going to change/add something in the server you should use POST request(not in your case)

if the http request is going to grab something using some data given by the client you should use GET query parameter to pass data to the server

KarimS
  • 3,812
  • 9
  • 41
  • 64