0

I want to expose URLs for user profiles in my web-app in the format:

example.com/user/<userId>

This should load the file user.html which contains JavaScript (ajax) code to load content based on the requested userId.

What options do I have to get userId parameter from the URL into my user.html file?

The way I can think of is to use a server-side language like PHP to embed the userId inside the HTML/JavaScript. Would like to see if there are other better options.

  • You are probably looking for a "routing" mechanism or even a framework like AngularJS, which does this kind of thing – chrki Oct 13 '15 at 22:13
  • What you're actually describing is url rewriting. You can achieve this using a [Rewrite Engine](https://en.wikipedia.org/wiki/Rewrite_engine). Most servers include some kind of Rewrite Engine, or some other method of achieving the same effect. Please do some more research on the subject, then come back when you have a more specific question. As it is, this question is either Unclear or Too Broad, both are off-topic for Stack Overflow. –  Oct 13 '15 at 22:55
  • My question is actually to do with passing the URL parameter into the Javascript code. I mentioned the exposed URL to provide some additional context. I guess if you want me to be even more specific, I could ask instead how do I get my URL parameter into a JavaScript variable rather than printing/embedding it inside the HTML on the server side. The suggestion from @chrki with routing is what I am looking for. –  Oct 14 '15 at 11:41

2 Answers2

1

You can do something like that:

var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.search; // => "?search=test"
parser.hash; // => "#hash"
parser.host; // => "example.com:3000"

More

http://www.sitepoint.com/url-parsing-isomorphic-javascript/

ksnietka
  • 105
  • 7
0

The best way would be to use a get in the form of example.com/user?userid=1 this questions may help you How to retrieve GET parameters from javascript? This really sounds like a job for something like php though.

Community
  • 1
  • 1
Mav2287
  • 796
  • 2
  • 9
  • 22