php将字符串化对象设置为null


php gets stringified object as null

我正试图用jquery ajax将一些信息传递到php页面。我真的不明白为什么php页面一直在回复我发送的字符串化JSON是空

//php
if ($type == "new" || $type == "update"){
    $new_address = json_decode($_REQUEST['address'], true);
    echo json_encode($new_address); //Null
}
//js
var string_encoded_address = JSON.stringify(address_obj.address);
string_encoded_address = encodeURIComponent(string_encoded_address);
console.log(string_encoded_address);
$.ajax({
    type: "post",
    url: "order_queries_templates/queries/address.php",
    data: "type=new&user_id=" + user_id + "&address=" + string_encoded_address,
    dataType: "json",
    success: function (returnedData) {
        console.log(returnedData);
    }
});

这为我的data属性提供了一个字符串:

type=new&user_id=8244&address=%7B%22companyName%22%3A%22test%20company%22%2C%22address1%22%3A%222420%20sample%20Road%22%2C%22city%22%3A%22SIOUX%20CITY%22%2C%22state%22%3A%22IA%22%2C%22zip%22%3A%2251106%22%2C%22cityStateZip%22%3A%22SIOUX%20CITY%2C%20IA%2051106%22%7D 

它可能出了什么问题?谢谢

您的代码不能工作的原因是您启用了magic_quotes_gpc。它将转义添加到双引号中,使用以下cli脚本可以看出:

$s = 'address=%7B%22companyName%22%3A%22test%20company%22%7D';
// parse query string into array
parse_str($s, $a);
// print address portion
echo $a['address'], "'n";
php -dmagic_quotes_gpc=On test.php

输出:

{'"companyName'":'"test company'"}

附加的转义中断json_decode(),因此返回null

关闭magic_quotes_gpc将通过使用.htaccess或编辑php.ini来解决此特定问题。

然而,让jQuery为您处理序列化要容易得多:

$.ajax({
    ...,
    data: {
      type:'new', 
      user_id: user_id, 
      adress: address_obj.address
    },
    ...
});

在这种情况下,您不再需要在服务器上使用json_decode(),只需直接引用$_POST['address']即可。