Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

javascript - 用JavaScript编码URL?(Encode URL in JavaScript?)

How do you safely encode a URL using JavaScript such that it can be put into a GET string?

(如何使用JavaScript安全地编码URL,以便可以将其放入GET字符串中?)

var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;

I assume that you need to encode the myUrl variable on that second line?

(我假设您需要在第二行编码myUrl变量?)

  ask by nickf translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Check out the built-in function encodeURIComponent(str) and encodeURI(str) .

(签出内置函数encodeURIComponent(str)encodeURI(str) 。)


In your case, this should work:

(在您的情况下,这应该起作用:)

var myOtherUrl = 
       "http://example.com/index.html?url=" + encodeURIComponent(myUrl);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...