Javascript - 获取 location.pathname + location.search - 不占用所有部

Javascript - get location.pathname + location.search - not taking all parts

本文关键字:location search 获取 pathname Javascript      更新时间:2023-09-26

我正在编写接受实际location.pathname + location.seach的js函数,以便用户在点击back按钮时可以返回搜索结果页面。

示例网址:http://127.0.0.1:8000/search_for_book/?titel=&autor=doniyor#

function select_book(bookid){
  var backurl = String(window.location.pathname+window.location.search);
  //alert(backurl); //<---- this is giving the correct full path
  window.location = 'selected/?book_id=' + bookid + '&back=' + backurl;
}

但在最后一行中,函数只附加到?titel=并切断其余部分。 新的 URL 变成了这样:

http://127.0.0.1:8000/search_for_book/selected/?book_id=10&back=/search_for_book/?titel=

为什么会这样?我需要完整的Location.pathname和完整的Location.search。

有什么想法吗?

但在最后一行中,函数只附加到 ?titel= 并切断其余部分。

不,它没有。提醒/记录您分配给 window.location 的字符串值会向您显示这一点。(顺便说一句,window.location.href是更新位置的正确方法。 location本身是一个对象,而不是一个属性——只有浏览器的容错能力才能让你这样做。因此,请改用window.location.href = …

这是错误的,因为 URL 中的&将参数彼此分开。因此,参数的值back&之后结束,然后出现一个新的参数autor - 因为您忽略了正确对参数值进行URL编码。

在将值添加到字符串之前,对值使用 encodeURIComponent