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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化