1

我正在尝试使用 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 

它有什么问题?谢谢!

4

1 回答 1

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']直接引用即可。

于 2013-02-13T23:49:27.967 回答