![](/img/trans.png)
[英]What's the easiest way to set a variable to be what the user types as a command?
[英]What is the easiest way to read a single variable in a URL?
使用Tumblr API,我正在使用其ID號來構建帖子的錨點,這樣的想法是,如果我可以從URL中讀取變量,則可以使用另一個腳本使用該ID查找單個帖子並將其構建在我的帖子上網站上,讓觀眾留在我的頁面上,而不是去Tumblr。 最簡單的方法是什么?
以下是該URL的示例:
nevermorestudiosonline.com/singlepost.php?id=123456789
簡單明了,我想從URL中讀取ID號並將其存儲到變量中,以供API調用使用以獲取帖子。 我只是不知道如何從URL到變量獲取ID。
您可以使用querystring
模塊從URL中提取ID。
var querystring = require('querystring');
var url = "nevermorestudiosonline.com/singlepost.php?id=123456789"
var id = querystring.parse(url)["id"];
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);
您可以訪問location.search,這將使您從?
URL末尾或片段標識符(#foo)開頭的字符,以先到者為准。
您可以使用以下代碼:
<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.