简体   繁体   English

如何在JavaScript和PHP中编码URL?

[英]How to encode URL in JavaScript and PHP?

I want to send a URL in a POST request in a variable called surl . 我想在一个名为surl的变量的POST请求中发送URL。 How should I encode it in JavaScript and decode it in PHP? 我应该如何在JavaScript中对其进行编码并在PHP中对其进行解码? For example, the value of surl could be http://www.google.co.in/search?q=javascript+urlencode+w3schools . 例如, surl的值可以是http://www.google.co.in/search?q=javascript+urlencode+w3schools

EDIT 编辑

Sorry, I forgot to mention, it's not form submission but a ajax request. 抱歉,我忘了提,这不是表单提交,而是ajax请求。

You don't need to to anything. 您什么都不需要。 Send it as is. 照原样发送。 Browser and PHP will do all escaping and unescaping for you (if you use form.surl.value = surl; form.submit() and $_POST['surl'] ). Browser和PHP将为您进行所有转义和转义(如果您使用form.surl.value = surl; form.submit()$_POST['surl'] )。 Or you can just use the plain form without any JavaScript (if it fulfills your needs). 或者,您可以直接使用不带任何JavaScript的纯格式(如果它满足您的需求)。

Replying henasraf's comment. 回复henasraf的评论。 Try this. 尝试这个。

<form id="form" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post"
    onsubmit="this.via_js.value=this.via_plain_form.value;">
<input type="hidden" name="via_js"/>
<input type="text" name="via_plain_form" value="Paste you url here"/>
<input type="submit" name="submit" value="Submit"/>
</form>

<?php

if (isset($_POST['submit'])) {
    var_export($_POST);
}

?>

For http://www.google.co.in/search?q=javascript+urlencode+w3schools , it outputs 对于http://www.google.co.in/search?q=javascript+urlencode+w3schools ,它输出

array (
    'via_js' => 'http://www.google.co.in/search?q=javascript+urlencode+w3schools',
    'via_plain_form' => 'http://www.google.co.in/search?q=javascript+urlencode+w3schools',
    'submit' => 'Submit',
)

Use encodeURIComponent(uri) (for encoding) and decodeURIComponent(uri) for decoding, 使用encodeURIComponent(uri) (用于编码)和decodeURIComponent(uri)进行解码,

Eg (encoding). 例如(编码)。

var uri="http://w3schools.com/my test.asp?name=ståle&car=saab";
document.write(encodeURIComponent(uri));

Output 产量

http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab HTTP%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab

Decoding is left for the reader. 解码留给读者。 :-) :-)

Source: http://www.w3schools.com/jsref/jsref_encodeURIComponent.asp 资料来源: http : //www.w3schools.com/jsref/jsref_encodeURIComponent.asp

至于PHP,它是urlencode()urldecode()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM