我正在尝试使用 jquery ajax 将一些信息传递到 php 页面。我真的不明白为什么 php 页面不断回显我发送的 strinified 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']
即可。
关于php 将字符串化对象获取为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14864902/