jsÔõô»ñÈ¡?ºóÃæµÄ²ÎÊý
javascript »ñÈ¡ url ÅÌÎʲÎÊýÓÐÁ½ÖÖÒªÁ죺ʹÓà window.location.search ÊôÐÔ´ÓÅÌÎÊ×Ö·û´®ÖÐÌáÈ¡²ÎÊý¡£ÊµÀý»¯ urlsearchparams ¹¤¾ß£¬ËüÌṩÁ˸üÀû±ãµÄ get() ºÍ getall() ÒªÁìÀ´»ñÈ¡²ÎÊýÖµ£¬ÒÔ¼°²Ù×÷ÅÌÎʲÎÊýµÄ¹¦Ð§¡£
ÔõÑùʹÓà JavaScript »ñÈ¡ URL ÅÌÎʲÎÊý
JavaScript ÌṩÁËÁ½ÖÖ³£ÓõÄÒªÁìÀ´»ñÈ¡ URL ÅÌÎʲÎÊý£º
1. window.location.search
window.location.search ÊôÐÔ°üÀ¨Ä¿½ñ URL µÄÅÌÎÊ×Ö·û´®²¿·Ö¡£ÀýÈ磺
const url = "https://example.com?name=John&age=30"; const searchParams = window.location.search; console.log(searchParams); // outputs: "?name=John&age=30"
µÇ¼ºó¸´ÖÆ
Òª»ñÈ¡µ¥¸ö²ÎÊý£¬¿ÉÒÔʹÓà substring() º¯Êý´ÓÅÌÎÊ×Ö·û´®ÖÐÌáÈ¡Ìض¨µÄ²¿·Ö¡£ÀýÈ磺
const nameParam = searchParams.substring(searchParams.indexOf("name=") + 5, searchParams.indexOf("&")); console.log(nameParam); // outputs: "John"
µÇ¼ºó¸´ÖÆ
2. URLSearchParams ¹¤¾ß
URLSearchParams ¹¤¾ßÌṩÁ˸üÀû±ãµÄ·½·¨À´´¦ÀíÅÌÎʲÎÊý¡£Ëü¿ÉÒÔ´Ó window.location.search ÖÐʵÀý»¯£¬²¢ÌṩÁË get() ºÍ getAll() ÒªÁìÀ´»ñÈ¡²ÎÊýÖµ¡£ÀýÈ磺
const url = "https://example.com?name=John&age=30"; const params = new URLSearchParams(window.location.search); const name = params.get("name"); const age = params.get("age"); console.log(name, age); // outputs: "John" "30"
µÇ¼ºó¸´ÖÆ
URLSearchParams ¹¤¾ß»¹ÔÊÐíÄúÌí¼Ó¡¢É¾³ýºÍÉèÖòÎÊýÖµ¡£ÀýÈ磬Ҫ½«Ð²ÎÊýÌí¼Óµ½ URL ÖУº
params.set("newParam", "value"); console.log(window.location.search); // outputs: "?name=John&age=30&newParam=value"
µÇ¼ºó¸´ÖÆ
Ñ¡ÔñÄÄÖÖÒªÁì»ñÈ¡ÅÌÎʲÎÊýÈ¡¾öÓÚÄúµÄÌض¨ÐèÇóºÍÆ«ºÃ¡£ÈôÊÇÄúÐèÒª¸üϸÄåµÄ¿ØÖƺÍʹÓÃÅÌÎʲÎÊý£¬URLSearchParams ¹¤¾ßÌṩÁ˸üÇ¿Ê¢ÇÒÒ×ÓÚʹÓõĹ¦Ð§¡£
ÒÔÉϾÍÊÇjsÔõô»ñÈ¡?ºóÃæµÄ²ÎÊýµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡