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 nslt的可用模型,或者其他可以进行推理的现有模型
  • ¥15 arduino上连sim900a实现连接mqtt服务器
  • ¥15 vncviewer7.0安装后如何正确注册License许可证,激活使用
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并2
  • ¥66 关于人体营养与饮食规划的线性规划模型
  • ¥15 基于深度学习的快递面单识别系统
  • ¥15 Multisim仿真设计地铁到站提醒电路
  • ¥15 怎么用一个500W电源给5台60W的电脑供电
  • ¥15 请推荐一个轻量级规则引擎,配合流程引擎使用,规则引擎负责判断出符合规则的流程引擎模板id