AJAX POST和加号(+) - 如何恩code? [英] AJAX POST and Plus Sign ( + ) -- How to Encode?

查看:166
本文介绍了AJAX POST和加号(+) - 如何恩code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我张贴通过AJAX的表单字段的内容保存到一个PHP脚本,并使用Javascript EN code(field_contents)。的问题是,任何加号被剥离并用空格取代。我怎样才能安全地恩code'的加号,然后适当地去code'它在PHP端?

I'm POSTing the contents of a form field via AJAX to a PHP script and using Javascript encode(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?

推荐答案

使用EN codeURIComponent()的JS和PHP,你应该得到正确的价值观。

Use encodeURIComponent() in JS and in PHP you should receive the correct values.

请注意:当您访问 $ _ GET $ _ POST $ _ REQUEST 在PHP中,要检索的已去codeD值。

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']; // "+"

这仅仅是一个包含URL连接codeD数据的原始HTTP请求。

It is only the raw HTTP request that contains the url encoded data.

对于GET请求,您可以从 URI检索此。 $ _ SERVER ['REQUEST_URI'] $ _ SERVER ['QUERY_STRING'] 。对于urlen codeD POST,的file_get_contents(PHP://标准输入')

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')

注:

德code()仅适用于连接codeD字符单字节。它不会对完整的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等价于:逃生('\ XC4 \ X80')

这是字节序列(<$ C C $> \ XC4 \ X80 )的重新presents在UTF-8。所以,如果你使用EN codeURIComponent()您的服务器端必须知道它正在接收UTF-8。否则PHP将裂伤的编码。

Which is the byte sequence (\xc4\x80) 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和加号(+) - 如何恩code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆