Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

javascript - 如何从GET参数获取值?(How to get the value from the GET parameters?)

I have a URL with some GET parameters as follows:

(我有一个带有一些GET参数的URL,如下所示:)

www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 

I need to get the whole value of c .

(我需要得到c的整个值。)

I tried to read the URL, but I got only m2 .

(我尝试读取URL,但是只有m2 。)

How do I do this using JavaScript?

(如何使用JavaScript执行此操作?)

  ask by joe translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

JavaScript itself has nothing built in for handling query string parameters.

(JavaScript 本身没有内置处理查询字符串参数的内容。)

Code running in a (modern) browser you can use the URL object (which is part of the APIs provided by browsers to JS):

(在(现代)浏览器中运行的代码可以使用URL对象 (这是浏览器为JS提供的API的一部分):)

 var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; //window.location.href var url = new URL(url_string); var c = url.searchParams.get("c"); console.log(c); 


For older browsers (including Internet Explorer), you can use this polyfill or the code from the original version of this answer that predates URL :

(对于较旧的浏览器(包括Internet Explorer),您可以使用此polyfill或该答案的原始版本中早于URL :)

You could access location.search , which would give you from the ?

(您可以访问location.search ,这将为您带来?)

character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.

(URL末尾或片段标识符(#foo)开头的字符,以先到者为准。)

Then you can parse it with this:

(然后,您可以使用以下代码解析它:)

 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("="); var key = decodeURIComponent(pair[0]); var value = decodeURIComponent(pair[1]); // If first entry with this name if (typeof query_string[key] === "undefined") { query_string[key] = decodeURIComponent(value); // If second entry with this name } else if (typeof query_string[key] === "string") { var arr = [query_string[key], decodeURIComponent(value)]; query_string[key] = arr; // If third or later entry with this name } else { query_string[key].push(decodeURIComponent(value)); } } return query_string; } var query_string = "a=1&b=3&c=m2-m3-m4-m5"; var parsed_qs = parse_query_string(query_string); console.log(parsed_qs.c); 

You can get the query string from the URL of the current page with:

(您可以使用以下方法从当前页面的URL获取查询字符串:)

var query = window.location.search.substring(1);
var qs = parse_query_string(query);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...