I have a script that posts a large object with AJAX after JSON.stringify().

When I am trying to decode it in PHP using json_decode($object, true); it won't be decoded.

My object looks something like:

var object = [
    {field_name:"Date & Time", some_other_value:"somevalue1"}
]

I am fairly sure it has something to do with the Date & Time. I am pretty sure that when I build the object, the value I insert into field_name is Date & Time

In PHP I've tried:

json_decode($object, true);
json_decode(utf8_decode($object))// with true as well.
json_decode(htmlentities($object, ENT_QUOTES, "UTF-8");

None seem to work.

UPDATE: I used alert() on the stringify and this is what i get:

"fields":{"29411502":{"id":29411502,"name":"Date & Time","functionName":""}}

Anyone with an idea ?

有帮助吗?

解决方案

In-case someone cares about the solution:

I had to us encodeURIcomponenet() on the stringified object.

其他提示

If you remove the & characters is the PHP script suddenly able to decode the object correctly?

Is so, might you need double encoding on the ampersand character? Is it possible it's getting decoded prior to the remainder of your message and causing a break in the parse?

This:

<?php

var_dump(
    json_decode(
        '[
            {"field_name":"Date &amp; Time", "some_other_value":"somevalue1"},
            {"field_name":"Date &amp; Time", "some_other_value":"somevalue2"},
            {"field_name":"Date &amp; Time", "some_other_value":"somevalue3"}
        ]'
    ),
    json_last_error(),
    PHP_VERSION
);

?>

Results in:

array(3) {
  [0]=>
  object(stdClass)#1 (2) {
    ["field_name"]=>
    string(15) "Date &amp; Time"
    ["some_other_value"]=>
    string(10) "somevalue1"
  }
  [1]=>
  object(stdClass)#2 (2) {
    ["field_name"]=>
    string(15) "Date &amp; Time"
    ["some_other_value"]=>
    string(10) "somevalue2"
  }
  [2]=>
  object(stdClass)#3 (2) {
    ["field_name"]=>
    string(15) "Date &amp; Time"
    ["some_other_value"]=>
    string(10) "somevalue3"
  }
}
int(0)
string(17) "5.3.15-pl0-gentoo"

Seems right to me...

Works for me

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 &amp; 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));

Produces a nice popup of

string(26) "[{"this":"is &amp; test"}]"
array(1) {
  [0] =>
  array(1) {
    'this' =>
    string(13) "is &amp; test"
  }
}

place single quotes around parameter and value

var object = [
{'field_name':'Date &amp; Time', 'some_other_value':'somevalue1'},
....
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top