douhuan3448 2013-02-13 22:58
浏览 74
已采纳

php将字符串化对象作为null

I'm trying to pass a some information to a php page with jquery ajax. I really can't understand why the php page keeps echoing back that the strinified JSON i'm sending is null

//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);
    }
});

this gives me a string for my data property:

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 

What could be wrong with it? Thanks!

  • 写回答

1条回答 默认 最新

  • dongwei3151 2013-02-13 23:49
    关注

    The reason why your code doesn't work is because you have magic_quotes_gpc enabled. It adds escaping to the double quotes, as can be seen using this cli script:

    $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'], "
    ";
    
    php -dmagic_quotes_gpc=On test.php
    

    Output:

    {\"companyName\":\"test company\"}
    

    The additional escaping breaks json_decode() so it returns null.

    Turning magic_quotes_gpc off will fix this particular issue, either by using .htaccess or editing the php.ini.

    However, it's far easier to just let jQuery take care of the serialization for you:

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

    In this case you won't have to json_decode() on the server anymore, just reference $_POST['address'] directly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算