透過編碼將查詢字串傳輸到Web 伺服器時,在escape()、encodeURI 之間選擇適當的編碼方法(),並且encodeURIComponent()很關鍵。
強烈建議避免使用 escape()。由於潛在的安全漏洞,ECMAScript 規範的附錄 B 明確建議不要使用它。
encodeURI() 應該用於建構功能齊全的 URL。它可以正確處理空格和其他字符,而不會破壞 URL 結構。例如,使用encodeURI()編碼「http://www.example.org/a file with space.html」將產生「http://www.example.org/a file with space.html」。
encodeURIComponent() 適合對 URL 參數的值進行編碼。它安全地轉義可能幹擾參數解析的字元。例如,使用encodeURIComponent()編碼「http://example.org/?a=12&b=55」將會得到「http://example.org/�a=12&b=55。」
const url = "http://example.net/?param1=" + encodeURIComponent("http://example.org/?a=12&b=55") + "¶m2=99";
此範例正確編碼參數值,同時保留整個 URL 的完整性。
以上是EncodeURI、encodeURIComponent 或 escape():我應該使用哪種編碼方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!