gpt4 book ai didi

javascript - 在 php 或 javascript 中向 url 添加参数后,如何修复刷新页面?

转载 作者:行者123 更新时间:2023-11-30 19:41:41 25 4
gpt4 key购买 nike

我正在尝试用 php 和 javascript 刷新页面,但它无法正常工作。我使用了多种功能和代码,但找不到好的答案。我使用了下面的 javascript 代码。但它会刷新多次且不停。

function insertParam(key, value)
{
key = encodeURI(key); value = encodeURI(value);

var kvp = document.location.search.substr(1).split('&');

var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');

if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
break;
}
}

if(i<0) {kvp[kvp.length] = [key,value].join('=');}

//this will reload the page, it's likely better to store this until finished
document.location.search = kvp.join('&');
}

我也用:

var url = window.location.href;    
if (url.indexOf('?') > -1){
url += '&param=1'
}else{
url += '?param=1'
}
window.location.href = url;

但 id 将参数添加到 url infinity。我只想在 url 中添加一个参数或两个参数。我该如何解决?谢谢。

最佳答案

检查你的 paramName 是否存在,如果不存在则重新加载 param:

var paramName = 'param';

var url = new URL(window.location.href);

var searchParams = new URLSearchParams(url.search);
if (!searchParams.get(paramName)) {
searchParams.append(paramName, 'value');

url.search = searchParams.toString();
window.location.href = url.toString();
}

或者你可以在 php 中使用 $_GET 来渲染 js 代码是否重新加载。

关于javascript - 在 php 或 javascript 中向 url 添加参数后,如何修复刷新页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55325659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com