AJAX POST 和加号 (+)——如何编码? [英] AJAX POST and Plus Sign ( + ) -- How to Encode?
问题描述
我正在通过 AJAX 将表单字段的内容发布到 PHP 脚本,并使用 JavaScript 来escape(field_contents)
.问题是任何加号都被删除并被空格取代.如何安全地编码"加号,然后在 PHP 端适当地解码"它?
I'm POSTing the contents of a form field via AJAX to a PHP script and using JavaScript to escape(field_contents)
. The problem is that any plus signs are being stripped out and replaced by spaces. How can I safely 'encode' the plus sign and then appropriately 'decode' it on the PHP side?
推荐答案
在 JS 和 PHP 中使用 encodeURIComponent()
您应该会收到正确的值.
Use encodeURIComponent()
in JS and in PHP you should receive the correct values.
注意:当您在 PHP 中访问 $_GET
、$_POST
或 $_REQUEST
时,您正在检索已解码的值.
Note: When you access $_GET
, $_POST
or $_REQUEST
in PHP, you are retrieving values that have already been decoded.
示例:
在你的 JS 中:
// url encode your string
var string = encodeURIComponent('+'); // "%2B"
// send it to your server
window.location = 'http://example.com/?string='+string; // http://example.com/?string=%2B
在您的服务器上:
echo $_GET['string']; // "+"
只有原始 HTTP 请求包含 url 编码数据.
It is only the raw HTTP request that contains the url encoded data.
对于 GET 请求,您可以从 URI 中检索它.$_SERVER['REQUEST_URI']
或 $_SERVER['QUERY_STRING']
.对于 urlencoded POST,file_get_contents('php://stdin')
For a GET request you can retrieve this from the URI. $_SERVER['REQUEST_URI']
or $_SERVER['QUERY_STRING']
. For a urlencoded POST, file_get_contents('php://stdin')
注意:
decode()
仅适用于单字节编码字符.它不适用于完整的 UTF-8 范围.
decode()
only works for single byte encoded characters. It will not work for the full UTF-8 range.
例如:
text = "u0100"; // Ā
// incorrect
escape(text); // %u0100
// correct
encodeURIComponent(text); // "%C4%80"
注意:"%C4%80"
等价于:escape('xc4x80')
在UTF-8中代表Ā
的字节序列(xc4x80
).因此,如果您使用 encodeURIComponent()
,您的服务器端必须知道它正在接收 UTF-8.否则 PHP 将破坏编码.
Which is the byte sequence (xc4x80
) that represents Ā
in UTF-8. So if you use encodeURIComponent()
your server side must know that it is receiving UTF-8. Otherwise PHP will mangle the encoding.
这篇关于AJAX POST 和加号 (+)——如何编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!