【发布时间】:2019-09-04 08:18:10
【问题描述】:
在我的网站上,我重写了所有网址。但是现在我已经开始使用 AJAX 来实现投票功能(它是一个问答社区),存在一些问题:
我将new UrlSearchParams(window.location.search) 存储在一个常量中。然后我为此调用.get() 方法。但是,由于 url 被重写,它无法识别查询。
const myParam = urlParams.get('id');
网址是www.example.com/Questions/7改写自www.example.com/pages/question.php?id=7
我的 .htaccess 文件如下所示:
RewriteEngine On # Turn on the rewriting engine
Options -MultiViews
RewriteRule ^$ /pages/index.php [L]
RewriteRule ^users/([0-9]+)$ pages/profile.php?id=$1 [NC] # Handle users
RewriteRule ^questions/([0-9]+)$ pages/question.php?id=$1 [NC] # Handle questions
RewriteRule ^([A-Za-z_]+)$ pages/$1.php [NC] # Handle pages
RewriteRule ^([A-Za-z_]+)$ pages/$1.html [NC] # Handle pages
如何克服 URL 重写时 UrlSearchParams 无法识别查询字符串数据这一事实?
【问题讨论】:
-
我用的是localhost根目录下的.htaccess文件
-
您必须通过解析
window.location.pathname来更改它以匹配新的 URL 格式……或者只是在 HTML 中的某个地方从 PHP 传递它,这可能更简单、更灵活。 -
如果 URL 被重写,则不能使用相同的代码从 URL 中获取信息。你需要不同的代码。在你的情况下,
location.pathname.substring(location.pathname.lastIndexOf('/'))... -
解析路径名的替代方法是在脚本标签中传递一个小对象变量
-
把这个放到你的
<head>部分~<script>const ID_PARAM = <?= json_encode($_GET['id'] ?? null) ?></script>
标签: javascript query-string querystringparameter