简体   繁体   English

有哪些选项可以将URL参数传递到JavaScript应用程序中

[英]What options are there for passing URL parameter into a JavaScript application

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 . 这应该加载文件user.html ,其中包含JavaScript(ajax)代码以根据请求的userId加载内容。

What options do I have to get userId parameter from the URL into my user.html file? 我需要什么选项才能将URL中的userId参数添加到user.html文件中?

The way I can think of is to use a server-side language like PHP to embed the userId inside the HTML/JavaScript. 我能想到的方法是使用PHP之类的服务器端语言将userId嵌入HTML / JavaScript中。 Would like to see if there are other better options. 想看看是否还有其他更好的选择。

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/ http://www.sitepoint.com/url-parsing-isomorphic-javascript/

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? 最好的方法是使用example.com/user?userid=1形式的get方法,该问题可能对您帮助。 如何从javascript中检索GET参数? This really sounds like a job for something like php though. 这听起来确实像php之类的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM