javascript `$('#form').serialize()` 弄乱了 UTF-8 字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8496540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:38:01  来源:igfitidea点击:

`$('#form').serialize()` messes up UTF-8 characters

javascriptencoding

提问by lisovaccaro

I'm inserting a form with AJAX and I'm using: $('#form').serialize()to get all the input and send it to insert.php.

我正在使用 AJAX 插入一个表单,我正在使用:$('#form').serialize()获取所有输入并将其发送到 insert.php。

The problem is that characters like ábecome %A9and such.

问题是像á变成%A9这样的字符。

How can I prevent this from happening before sending it or how get the correct characters when I retrieve it through $_POST so I can insert them correctly to my database?

如何在发送之前防止这种情况发生,或者在通过 $_POST 检索时如何获取正确的字符,以便我可以将它们正确插入到我的数据库中?

EDIT -----

编辑 - - -

Btw: Same Form with no AJAX, just action="POST" to the SAME insert.php inserts correctly, so the problem is solely with serialize() messing the HTML.

顺便说一句:没有 AJAX 的相同表单,只是 action="POST" 到 SAME insert.php 正确插入,所以问题仅在于 serialize() 弄乱了 HTML。

回答by Daniel Moses

Jquery serialize()serializes as UTF-8. So ábecomes the correct UTF-8 encoding %c3%a1. Try using the $_REQUESTas that is already decoded as per the php documentation. here

Jqueryserialize()序列化为 UTF-8。所以á就变成了正确的 UTF-8 编码%c3%a1。尝试使用$_REQUEST已经按照 php 文档解码的 as。这里

回答by Zazú Perú

The final step you need to do is to decode in your PHP file like this:

您需要做的最后一步是在您的 PHP 文件中进行解码,如下所示:

$usuario=utf8_decode($_POST['nombre']);

$usuario=utf8_decode($_POST['nombre']);

I use to combine utf8_decode() with htmlspecialchars() before sending datas to the database:

在将数据发送到数据库之前,我使用 utf8_decode() 与 htmlspecialchars() 组合:

$nombres = utf8_decode(htmlspecialchars($_POST['nombres']));

$nombres = utf8_decode(htmlspecialchars($_POST['nombres']));