Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用php/javascript仅显示url中的特定参数?_Javascript_Php - Fatal编程技术网

如何使用php/javascript仅显示url中的特定参数?

如何使用php/javascript仅显示url中的特定参数?,javascript,php,Javascript,Php,我有几个参数可以传递给页面,比如来自数据库的唯一id、错误消息和表单数据。我想隐藏所有这些参数,以保持url干净,除了id。我尝试在PHP和JavaScript中查找这些参数,但没有找到解决方案,所以我开始四处摆弄 如果在隐藏id后刷新页面,路由将无法再找到id,这将在页面上生成一系列错误。我想隐藏除id之外的所有参数,这样就不会出现这些错误。我使用这段Javascript成功地删除了所有参数: let clean_url = window.location['href'].split('?')

我有几个参数可以传递给页面,比如来自数据库的唯一id、错误消息和表单数据。我想隐藏所有这些参数,以保持url干净,除了id。我尝试在PHP和JavaScript中查找这些参数,但没有找到解决方案,所以我开始四处摆弄

如果在隐藏id后刷新页面,路由将无法再找到id,这将在页面上生成一系列错误。我想隐藏除id之外的所有参数,这样就不会出现这些错误。我使用这段Javascript成功地删除了所有参数:

let clean_url = window.location['href'].split('?')[0];
window.history.pushState(null, null, clean_url);
如果设置了id,我试图只显示id(它总是一个正整数),但是当将我的JS更改为下一个代码块时,它会再次显示所有参数

let url_string = window.location['href'];
let url = new URL(url_string);
let id = url.searchParams.get("id");
if (typeof id !== 'undefined') {
    let clean_url = url_string.split('?')[0].concat("?id={0}".format(id));
} else {
    let clean_url = window.location['href'].split('?')[0];
}
window.history.pushState(null, null, clean_url);
有谁能告诉我我的代码有什么问题,或者它是否可以用php解决?提前谢谢

编辑:由于时间不足,我无法将我的反馈消息设置为$\u会话。我找到了修复javascript的方法,因此除了
id
参数之外的所有参数都被隐藏:

let url_string = window.location['href'];
let short_url = window.location['href'].split('?')[0];
let url = new URL(url_string);
let id = url.searchParams.get("id");
if (id == null) {
    window.history.pushState(null, null, short_url);
} else {
    let clean_url = short_url.concat(`?id=${id}`);
    window.history.pushState(null, null, clean_url);
}

为你的数据使用好的媒介

这并不总是正确的,但一个好的经验法则是错误消息进入$\u会话,表单数据进入$\u POST

例如,您的表单可能如下所示:

<form method="post" action="myurl1.php?id=123">
  <!--you could also use a hidden field to send the id with post : <input type="hidden" name="id" />-->
  <input name="test" />
</form>
关键是您决定如何发送数据,并且只有当url对您的用户有价值时,才应该使用url


(有关php会话的更多信息)

如果我理解了您的问题,您可以将您的id放入标记表单action=myurl中?as method=post。所以你只发送id,其他参数被隐藏。@Ferdinando这是否仍然会将其他参数发送到新路线?谢谢你的回答,但是由于我在这个项目上的时间限制,我将无法再更改它。不过,我会在下一个项目中记住这一点。
if(empty($_POST[test])){
  $_SESSION['error']='Empty test field';
}
header('Location: myurl2.php?id='.$_GET['id']); //or $_POST['id'] if you used a hidden field