我有一个脚本,在JSON.stringify()
之后发布一个带有AJAX的大对象。
当我尝试使用json_decode($object, true);
在PHP中解码它时,它不会被解码。
我的对象看起来像:
var object = [
{field_name:"Date & Time", some_other_value:"somevalue1"}
]
我确信这与Date & Time
有关。我非常确信,当我构建对象时,我插入到field_name中的值是Date & Time
在PHP中,我尝试过:
json_decode($object, true);
json_decode(utf8_decode($object))// with true as well.
json_decode(htmlentities($object, ENT_QUOTES, "UTF-8");
似乎都不起作用。
更新:我在字符串上使用了alert()
,这就是我得到的:
"fields":{"29411502":{"id":29411502,"name":"Date & Time","functionName":""}}
有人有想法吗?
如果有人关心解决方案:
我必须在字符串对象上使用encodeURIcomponenet()
。
如果删除&字符是PHP脚本突然能够正确解码对象吗?
是的,您是否需要对"与"字符进行双重编码?它是否可能在消息的剩余部分之前被解码,并导致解析中断?
这:
<?php
var_dump(
json_decode(
'[
{"field_name":"Date & Time", "some_other_value":"somevalue1"},
{"field_name":"Date & Time", "some_other_value":"somevalue2"},
{"field_name":"Date & Time", "some_other_value":"somevalue3"}
]'
),
json_last_error(),
PHP_VERSION
);
?>
结果:
array(3) {
[0]=>
object(stdClass)#1 (2) {
["field_name"]=>
string(15) "Date & Time"
["some_other_value"]=>
string(10) "somevalue1"
}
[1]=>
object(stdClass)#2 (2) {
["field_name"]=>
string(15) "Date & Time"
["some_other_value"]=>
string(10) "somevalue2"
}
[2]=>
object(stdClass)#3 (2) {
["field_name"]=>
string(15) "Date & Time"
["some_other_value"]=>
string(10) "somevalue3"
}
}
int(0)
string(17) "5.3.15-pl0-gentoo"
对我来说似乎是正确的…
适用于我的
test.html
<html>
<body>
<script src="js/jquery/jquery-2.0.3.js"></script>
<button id="bob">Click ME</button>
<script>
(function($){
$('#bob').click(function() {
$.ajax({
method: "POST",
url: "test.php",
data: JSON.stringify([{"this":"is & test"}]),
contentType: "text/javascript"
}).done(function(a) {
alert(a);
});
});
})(jQuery);
</script>
</body>
</html>
test.php
<?php
$data = file_get_contents("php://input");
var_dump($data);
var_dump(json_decode($data, true));
生成一个漂亮的弹出窗口
string(26) "[{"this":"is & test"}]"
array(1) {
[0] =>
array(1) {
'this' =>
string(13) "is & test"
}
}
在参数和值周围加单引号
var object = [
{'field_name':'Date & Time', 'some_other_value':'somevalue1'},
....