[英]What is the easiest way to read a single variable in a URL?
Using the Tumblr API, I'm constructing anchors to my posts using their ID numbers, with the idea that if I can read the variable from the URL, I can use another script to find a single post using that ID and construct it on my website, keeping my viewers on my page instead of leaving to go to Tumblr. 使用Tumblr API,我正在使用其ID号来构建帖子的锚点,这样的想法是,如果我可以从URL中读取变量,则可以使用另一个脚本使用该ID查找单个帖子并将其构建在我的帖子上网站上,让观众留在我的页面上,而不是去Tumblr。 What would be the easiest way to do that?
最简单的方法是什么?
Here's what the URL would be as an example: 以下是该URL的示例:
nevermorestudiosonline.com/singlepost.php?id=123456789
Plain and simple, I want to read the ID number from the URL and store it to a variable to be used by the API call to get the post. 简单明了,我想从URL中读取ID号并将其存储到变量中,以供API调用使用以获取帖子。 I just don't know how to get the ID from URL to variable.
我只是不知道如何从URL到变量获取ID。
You can use querystring
module to extract id from the URL. 您可以使用
querystring
模块从URL中提取ID。
var querystring = require('querystring');
var url = "nevermorestudiosonline.com/singlepost.php?id=123456789"
var id = querystring.parse(url)["id"];
JavaScript Way JavaScript方式
var url = 'nevermorestudiosonline.com/singlepost.php?id=123456789';
var temp = url.split('=');
var id = temp[1];
// Now you can play with this id and use it the way you
// you want.
console.log(id);`
var url = "nevermorestudiosonline.com/singlepost.php?id=123456789";
url = url.split("?")[1];
url = url.slice(url.indexOf("id=") + 3,url.length)
console.log(url);
You can access location.search , which will 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)开头的字符,以先到者为准。
The code you can use this: 您可以使用以下代码:
<script type="text/javascript">
var QueryString = function () {
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
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;
}();
console.log(QueryString);
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.