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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度