我试图用jquery ajax将一些信息传递到php页面。我真的无法理解为什么php页面会回应我发送的GSON我发送的空白
//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
它可能有什么问题?谢谢!
答案 0 :(得分:1)
您的代码无效的原因是您启用了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']
。