새로 고침 없이 URL에 매개 변수 추가
이전에도 여러 번 질문을 받았지만 답변이 제 문제를 해결하기에 충분하지 않았습니다.나는 페이지의 전체 URL을 변경하고 싶지 않습니다.매개 변수를 추가합니다.&item=brand
버튼 클릭 시 새로 고침 없이 클릭합니다.
사용.document.location.search += '&item=brand';
페이지를 새로 고칩니다.
사용.window.location.hash = "&item=brand";
새로 고치지 않고 해시만 포함하여 추가#
매개 변수의 사용/효과를 제거합니다.추가 후 해시를 제거하려고 했지만 작동하지 않았습니다.
이 답변과 많은 다른 답변들은 HTML5 History API의 사용을 사용할 것을 제안합니다.history.pushState
이전 브라우저의 경우 페이지가 다시 로드되지 않도록 fragment 식별자를 설정하는 방법입니다.하지만 어떻게요?
URL을 다음과 같이 가정합니다.http://example.com/search.php?lang=en
추가 방법&item=brand
출력이 다음과 같이 되도록 HTML5 pushState 메서드 또는 fragment 식별자를 사용합니다.http://example.com/search.php?lang=en&item=brand
페이지 새로 고침 없이?
HTML5 pushState를 사용하여 기존/현재 URL에 매개변수를 추가하는 방법 또는 동일한 목적으로 fragment 식별자를 설정하는 방법을 누군가가 밝혀줄 수 있기를 바랍니다.좋은 튜토리얼, 데모 또는 약간의 설명이 있는 코드 조각이 좋을 것입니다.
지금까지 제가 한 일에 대한 데모.답변해주시면 감사하겠습니다.
pushState 또는 replaceState 메서드를 사용할 수 있습니다. 예:
window.history.pushState("object or string", "Title", "new url");
OR
window.history.replaceState(null, null, "?arg=123");
인수가 있는 예제:
var refresh = window.location.protocol + "//" + window.location.host + window.location.pathname + '?arg=1';
window.history.pushState({ path: refresh }, '', refresh);
다음과 같이 매개 변수를 동시에 추가 및 제거하려는 경우에도 URL API를 사용할 수 있습니다.
const url = new URL(window.location.href);
url.searchParams.set('param1', 'val1');
url.searchParams.delete('param2');
window.history.replaceState(null, null, url); // or pushState
만약 누군가가 더 복잡한 url(즉, https://stackoverflow.com/questions/edit?newParameter=1), 에 파라미터를 추가하고 싶다면, 다음 코드가 저에게 효과가 있었습니다.
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?newParameter=1';
window.history.pushState({ path: newurl }, '', newurl);
이것이 도움이 되길 바랍니다!
수정된 메디 답변과 이것은 속임수를 썼습니다.
const insertParam = (key: string, value: string) => {
key = encodeURIComponent(key);
value = encodeURIComponent(value);
let kvp = window.location.search.substr(1).split('&');
if (kvp[0] === '') {
const path = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + key + '=' + value;
window.history.pushState({ path: path }, '', path);
} else {
let i = kvp.length; let 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('=');
}
const refresh = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + kvp.join('&');
window.history.pushState({ path: refresh }, '', refresh);
}
}
페이지를 다시 로드하지 않고 현재 URL에 여러 매개 변수를 추가하려면 다음을 시도하십시오.
window.history.replaceState(null, null, `?${$.param({
item: 'brand',
lang: 'en',
})}`);
$.param
개체를 다음으로 변환합니다.item=brand&lang=en
그럼 그냥 추가하세요.?
처음에
결과는 다음과 같습니다.httpts://app.com/index?item=brand&lang=en
export function getHash(hash: string, key: string): string | undefined {
return hash
.split("#")
.find((h) => h.startsWith(key))
?.replace(`${key}=`, "");
}
export function setHash(hash: string, key: string, value: string): string {
let hashArray = hash.split("#").filter((h) => !h.startsWith(key));
hashArray.push(`${key}=${value}`);
return hashArray.length > 0
? hashArray.reduce((s1, s2) => `${s1}#${s2}`)
: "";
}
export function deleteHash(hash: string, key: string): string {
let hashArray = hash.split("#").filter((h) => !h.startsWith(key));
return hashArray.length > 0
? hashArray.reduce((s1, s2) => `${s1}#${s2}`)
: "";
}
언급URL : https://stackoverflow.com/questions/32828160/appending-parameter-to-url-without-refresh
'programing' 카테고리의 다른 글
CORS(Cross-Origin Resource Sharing) - 여기에 누락된 내용이 있습니까? (0) | 2023.08.11 |
---|---|
excel vba selection.address에서 행, 셀 값 가져오기 (0) | 2023.08.11 |
비디오 요소를 올바르게 언로드/파괴하는 방법 (0) | 2023.08.11 |
asp.net core 2.0 - 값은 null일 수 없습니다.매개 변수 이름: connectionString (0) | 2023.08.11 |
APK 파일에서 프로젝트로 리버스 엔지니어링 (0) | 2023.08.11 |