我想从URL获取信息。
示例:mywesite.com/#base64text
如何使用浏览器js获取传入请求。在js中使用哪个函数
如果您需要做的只是提取标签符号之后的数据,那么只需像这样使用.split()
和location.href
:
const data = location.href.split('#', 2)[1];
如果你需要更进一步,在URL中存储JS对象,那么你应该使用base64编码的JSON。要生成编码数据并将其放入URL中,只需使用JSON.stringify()
和atob()
:
const obj = {
name: 'Bob',
age: 30,
};
location.href += '#' + btoa(JSON.stringify(obj));
// the page will now reload with the data stored in the URL
然后,解码数据,使用atob()
和JSON.parse()
:
const urlData = location.href.split('#', 2)[1];
const data = urlData ? JSON.parse(atob(urlData)) : null;
console.log(data);
// returns any data stored in URL, or null