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条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置