douji1077 2015-01-31 01:49
浏览 81
已采纳

使用来自AJAX对象的序列化数据和PHP

I'm sending an entire form, about 8 fields, along with my AJAX data object, one of which is a serialized string:

var fields = $(this).serialize();

var data = { 
    action:'newSubmission',
    nonce: Nonce,
    fields: fields
}; 

Now within PHP I cannot understand how to get each field value from the $_POST object correctly.

$test = $_POST['field'];

Is the full string and sends back to JS a properly formatted JSON object. But how do I break up the serialized string correctly in PHP?

  • 写回答

2条回答 默认 最新

  • dongquweng5152 2015-01-31 02:15
    关注

    The string will be encoded, so you will have to do that with url_decode. Here is a function that I used to build a workable object out of the string.

        function urldecode_to_obj($str) {
    
            $str = trim($str, '"');
    
            // explode string before decoding
            foreach (explode('&', $str) as $chunk) {
                $param = explode("=", $chunk);
    
                if ($param) {
    
                    // search string for array elements and look for key-name if exists
                    preg_match('#\[(.+?)\]$#', urldecode($param[0]), $with_key);
                    preg_match('#\[\]$#', urldecode($param[0]), $no_key);
    
                    $mkey = preg_split('/\[/', urldecode($param[0]));
    
                    // converts to array elements with numeric key
                    if ($no_key) {
                        $data[$mkey[0]][] = urldecode($param[1]);
                    }
    
                    // converts to array elements with named key
                    if ($with_key) {
                        $data[$mkey[0]][$with_key[1]] = urldecode($param[1]);
                    }
    
                    if (!$no_key && !$with_key) {
                        $data[urldecode($param[0])] = urldecode($param[1]);
                    }
    
                }
    
            }
    
            return (object)$data;
        }
    
    $str = "serialized_string";
    $obj = urldecode_to_obj($str);
    

    Your variables with values are now in the object. If you have a var1 variable in there with a value1:

    $obj -> var1 = "value1";
    

    You can also get thins back as an array. Just omit the (object) casting and return the data in t\he function as:

    return $data;
    

    If you want to return things to your JS then you should echo them out as an array and use json_encode:

    $array = array("success" => true);
    echo json_encode($array);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能