2

我有一个 javascript 对象,我想在使用 jQuery 的 ajax 实现时将其传递给 PHP 文件。

我试图直接将它传递给它,但这不起作用,因为它没有被转义或任何东西。我试过使用 JSON.stringify 但这对我也不起作用。

有没有办法将 javascript 对象“序列化”为 POST 字符串?

更新,我再次使用 JSON.stringify() 。结果是:

JSON.stringify() 的结果是:

{\"label\":\"Borne, Overijssel, Nederland\",\"value\":\"Borne, Overijssel, Nederland\",\"geocode\":{\"address_components\":[{\"long_name\":\"Borne\",\"short_name\":\"Borne\",\"types\":[\"locality\",\"political\"]},{\"long_name\":\"Borne\",\"short_name\":\"Borne\",\"types\":[\"administrative_area_level_2\",\"political\"]},{\"long_name\":\"Overijssel\",\"short_name\":\"OV\",\"types\":[\"administrative_area_level_1\",\"political\"]},{\"long_name\":\"Nederland\",\"short_name\":\"NL\",\"types\":[\"country\",\"political\"]}],\"formatted_address\":\"Borne, Nederland\",\"geometry\":{\"bounds\":{\"ca\":{\"b\":52.2832527,\"f\":52.3151634},\"ea\":{\"b\":6.688658900000064,\"f\":6.801415300000031}},\"location\":{\"Ya\":52.3002366,\"Za\":6.753725799999984},\"location_type\":\"APPROXIMATE\",\"viewport\":{\"ca\":{\"b\":52.2832527,\"f\":52.3151634},\"ea\":{\"b\":6.688658900000064,\"f\":6.801415300000031}}},\"types\":[\"locality\",\"political\"]}}

当我执行json_decode它时,结果为 NULL。有什么建议么?

4

2 回答 2

1

If your passing an object as a string thats in legitmate JSON format, to PHP try using

json_decode() on the php side of things. Example

<?php
   $ojb = json_decode($_POST['my_json_string']);
?>

What this will do is turn your object into an array or object depending on which version of PHP you are using, and in some cases the object will turn into an array with multiple objects in it.. example:

Array(
    [0] stdClass (
            'key1'=>'val1'
            'key2'=>'val2'
            'key3'=>'val3'
         )
)

which I know the above isnt a good representation, but its a representation in the lines there of.

After that PHP side you can work with the variable $ojb like any other array/object.

$something = $ojb[0]->key1;

EDIT I notice your string now. The fact that the quotes are escaped in the string, breaks the fact that its a JSON object, with that you can do one of two things.. Either just pass the object to PHP through your post/get as is, without running it through strigify or.. you could try on the PHP side, if there is a need to strigfy it..

$ojb = stripslashes($_POST['my_json_string']); $ojb = json_decode($ojb);

which will attempt to remove the slashes from the quotes, before putting it through the decode process.

http://php.net/manual/en/function.json-decode.php

于 2012-10-26T18:58:53.720 回答
0

您可以指定 POST 请求的原始正文。原始数据将是JSON.stringify调用的结果,这意味着您应该指定适当的Content-Type标头。

$.ajax(url, {
  type: 'POST',
  contentType: 'application/json',
  data: JSON.stringify(data),
  processData: false // prevent escaping and other processing
});

然后,您可以像这样在 PHP 中反序列化对象:

$json = file_get_contents('php://input');
$data = json_decode($json);

原始请求正文映射到特殊路径php://input

于 2012-10-26T22:13:34.513 回答