php - Json 编码从 Ajax 中给我 null,但从正常的 php 字符串中没有给我 null

标签 php ajax json jquery

大家好,这是 php 中的字符串(抱歉,如果很长)

$JsonSpecificheTitoli='{"titoli":{"TitoloEbay-1-Virtuemart":" Maglia Shirt Adidas Milan tg S M L Per sport d è numerico maniche corte Home ","TitoloEbay-2-EbayIT":" Maglia Shirt Adidas Milan tg M L Ibrahimovic Per sport d è numerico Home ","TitoloEbay-5-EbayIT":" Maglia Shirt Adidas Milan tg XL Per sport d è numerico maniche corte Home ","TitoloEbay-3-EbayDE":" Trikot Shirt Adidas Milan tg S M XL F�r Sport ist numerisch S/S Saison 09 10 ","TitoloEbay-6-EbayDE":" Trikot Shirt Adidas Milan tg L F�r Sport ist numerisch S/S Saison 09 10 Home ","TitoloEbay-4-EbayUK":" Jersey Shirt Adidas Milan tg L XL XXL For sports is numerically Kurze armel "},"specifiche":{"Virtuemart":{"":"Arrivo in 24/48 h con SDA oppure Possibilita di necessita di 4/5 giorni per la spedizione","Maniche":" maniche corte "},"EbayIT":{"":"Arrivo in 24/48 h con SDA oppure Possibilita di necessita di 4/5 giorni per la spedizione","Maniche":" maniche corte "},"EbayDE":{"":"Ankunft in 24/48 h M�glichkeit der SDA oder erfordert 4 / 5 Tage Versandkosten","Arme":" S/S "},"EbayUK":{"":"Arrival in 24/48 h Possibility of SDA or requires 4 / 5 days for shipping","Sleeves":" Kurze armel "}}}';

如果我直接使用 php 从该字符串进行 json_decode 没有问题:

$pr = json_decode($JsonSpecificheTitoli);  //-->OK

但是如果我从 REQUEST (来自 Ajax 请求)中获取它,它会给我 null

$Tt = $_REQUEST['Titoli'];
$TtJ = json_decode ($Tt); // --> it says null

$v=json_last_error();  //--> gives me 5 , is Syntax error? 

奇怪的是,请求、复制和打印中的相同字符串怎么会使其变坏?

谢谢

最佳答案

$v=json_last_error(); gives me 5 , is Syntax error?

您可以根据 the error constants 进行检查,例如 JSON_ERROR_SYNTAX,只需回显该值即可:

echo JSON_ERROR_SYNTAX; # 4
echo JSON_ERROR_UTF8;   # 5

所以在你的情况下这是一个UTF8错误。 json_decode­Docs 采用 UTF-8 编码字符串作为输入。只要确保它是 UTF-8 编码就可以了。

$_REQUEST(以及类似的输入变量)的编码取决于发送到您的应用程序的 HTTP 请求(输入)的编码,这取决于原始网站的编码/字符集通常情况下。

没有办法可靠地检测它,所以你最好了解它。但是,如果您需要检测它,mb_http_input­Docs 函数会很有帮助。

获取 PHP 脚本的 HTTP 请求中使用的编码信息,然后根据需要对传入数据进行重新编码,然后再将其传递到 json_decode 中。您可以借助 iconv function­DocsMultibyte String functions­Docs 重新编码 PHP 中的字符串。

此外,您还可以验证输入是否有效(有效的 UTF-8 字符串),如果不是,则拒绝接受对您的应用程序的无效请求。要检查字符串是否为 UTF-8,您可以对字符串运行正则表达式:

$isUTF8 = preg_match('//u', $string);

(另请参阅 How to detect malformed utf-8 string in PHP? )

关于php - Json 编码从 Ajax 中给我 null,但从正常的 php 字符串中没有给我 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8660164/

相关文章:

php - 如何在 CodeIgniter 中的 SQL 中列出 <select> 中的名称

php - 使用输出缓冲区的函数在开发中有效,但在生产中无效

javascript - CRUD 策略,每个 CRUD 操作使用一次还是两次调用?

android - 改造抛出错误预期为 BEGIN_ARRAY 但为 BEGIN_OBJECT

javascript - Angular - 在 ng-repeat 中使用 orderBy 以升序排列

php - 将 MySQL 连接到 Android

json - 从 Django 模型获取数据并使用 AJAX 在 html 表中显示

ajax - 谷歌如何加密/混淆http响应以使其几乎无法用肉眼读取?

json - 将 Clojure 字节数组编码为 JSON

php - 在 Woocommerce 中添加基于产品类别的自定义结帐字段