Javascript ajax 发布特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1954502/
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-08-22 22:03:19  来源:igfitidea点击:

ajax post special characters

javascriptajaxspecial-charactersencode

提问by Glenn

How do I pass a a large string containing characters like '%' and '&' to my php page through ajax post?

如何通过 ajax post 将包含 '%' 和 '&' 等字符的大字符串传递到我的 php 页面?

In other words how to javascript-encode them and php-decode them?

换句话说,如何对它们进行 javascript 编码和 php 解码?

回答by gahooa

the encodeURIComponent()JavaScript function can be used to escape any of those characters in either the keys or the values.

encodeURIComponent()JavaScript函数可用于转义任何这些字符的在任一键或值。

PHP will receive and decode it automatically into the $_POSTarray.

PHP 会自动接收并解码到$_POST数组中。

The format of the data should be Query String format, specifically:

数据格式应为Query String格式,具体为:

Content-Type: application/x-www-form-urlencoded

For example:

例如:

Name=Joe&Age=23&City=Altoona

If you use encodeURIComponent()on each key and each value, then join them with =, and group them by &, you won't have any further issues.

如果您encodeURIComponent()在每个键和每个值上使用,然后用 加入它们,然后用 将它们=分组&,您将不会有任何进一步的问题。

回答by Gabriel McAdams

To encode them in javascript, use encodeUri and encodeUriComponent

要在 javascript 中对它们进行编码,请使用 encodeUri 和 encodeUriComponent

http://www.w3schools.com/jsref/jsref_encodeURIComponent.asp

http://www.w3schools.com/jsref/jsref_encodeURIComponent.asp



PHP Decode:

PHP解码:

http://php.net/manual/en/function.urldecode.php

http://php.net/manual/en/function.urldecode.php

回答by alemjerus

You actually don't need to encode or decode something, if you use POST parameter in send method of XMLHttpRequest. Only GET needs such and encoding, since it uses URI field. You should be careful when using this data in SQL requests. Beware of injections.

如果您在 XMLHttpRequest 的 send 方法中使用 POST 参数,您实际上不需要编码或解码某些东西。只有 GET 需要此类和编码,因为它使用 URI 字段。在 SQL 请求中使用这些数据时应该小心。小心注射。