简体   繁体   English

如何从 PHP 中的 serializeArray 获取 POST 值?

[英]How to get the POST values from serializeArray in PHP?

I am trying this new method I've seen serializeArray() .我正在尝试这种我见过的新方法serializeArray()

//with ajax
var data = $("#form :input").serializeArray();
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc

So I get these key value pairs, but how do I access them with PHP?所以我得到了这些键值对,但是如何使用 PHP 访问它们?

I thought I needed to do this, but it won't work:我以为我需要这样做,但它不起作用:

// in PHP script
$data = json_decode($_POST['data'], true);

var_dump($data);// will return NULL?

Thanks, Richard谢谢,理查德

Like Gumbo suggested, you are likely not processing the return value of json_decode . 像Gumbo建议的那样,您可能无法处理json_decode的返回值。
Try 尝试

$data = json_decode($_POST['data'], true);
var_dump($data);

If $data does not contain the expected data, then var_dump($_POST); 如果$data不包含预期数据,则var_dump($_POST); to see what the Ajax call did post to your script. 查看Ajax调用发布到您的脚本的内容。 Might be you are trying to access the JSON from the wrong key. 您可能正在尝试从错误的密钥访问JSON。

EDIT 编辑
Actually, you should make sure that you are really sending JSON in the first place :) 实际上,你应该确保你真的在第一时间发送JSON :)
The jQuery docs for serialize state The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. 用于序列化状态的jQuery文档.serializeArray()方法创建一个JavaScript对象数组可以编码为JSON字符串。 Ready to be encoded is not JSON. 准备编码不是JSON。 Apparently, there is no Object2JSON function in jQuery so either use https://github.com/douglascrockford/JSON-js/blob/master/json2.js as a 3rd party lib or use http://api.jquery.com/serialize/ instead. 显然,jQuery中没有Object2JSON函数,所以要么使用https://github.com/douglascrockford/JSON-js/blob/master/json2.js作为第三方库,要么使用http://api.jquery.com/序列化/而不是。

The OP could have actually still used serializeArray() instead of just serialize() by making the following changes: 通过进行以下更改,OP实际上仍然可以使用serializeArray()而不是serialize():

//JS 
var data = $("#form :input").serializeArray();
data = JSON.stringify(data);
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc

// PHP
$data = json_decode(stripslashes($_POST['data']),true);
print_r($data); // this will print out the post data as an associative array

The JSON structure returned is not a string. 返回的JSON结构不是字符串。 You must use a plugin or third-party library to "stringify" it. 您必须使用插件或第三方库来“字符串化”它。 See this for more info: 有关详细信息,请参阅此

http://www.tutorialspoint.com/jquery/ajax-serializearray.htm http://www.tutorialspoint.com/jquery/ajax-serializearray.htm

its possible by using the serialize array and json_decode() 它可以通过使用序列化数组和json_decode()

// js
var dats = JSON.stringify($(this).serializeArray());
data: { values : dats } // ajax call

//PHP
 $value =  (json_decode(stripslashes($_REQUEST['values']), true));

the values are received as an array 值以数组形式接收

each value can be retrieved using $value[0]['value'] each html component name is given as $value[0]['name'] 可以使用$ value [0] ['value']检索每个值。每个html组件名称都以$ value [0] ['name']的形式给出

print_r($value) //gives the following result
Array ( [0] => Array ( [name] => name [value] => Test ) [1] => Array ( [name] => exhibitor_id [value] => 36 ) [2] => Array ( [name] => email [value] => test@gmail.com ) [3] => Array ( [name] => phone [value] => 048028 ) [4] => Array ( [name] => titles [value] => Enquiry ) [5] => Array ( [name] => text [value] => test ) ) 

I have a very similar situation to this and I believe that Ty W has the correct answer. 我有一个非常类似的情况,我相信Ty W有正确的答案。 I'll include an example of my code, just in case there are enough differences to change the result, but it seems as though you can just use the posted values as you normally would in php. 我将包含一个我的代码示例,以防万一有足够的差异来改变结果,但似乎你可以像通常在php中那样使用发布的值。

// Javascript
$('#form-name').submit(function(evt){
var data = $(this).serializeArray();
$.ajax({ ...etc...

// PHP
echo $_POST['fieldName'];

This is a really simplified example, but I think the key point is that you don't want to use the json_decode() method as it probably produces unwanted output. 这是一个非常简化的示例,但我认为关键点是您不想使用json_decode()方法,因为它可能会产生不需要的输出。

the javascript doesn't change the way that the values get posted does it? javascript不会改变值发布的方式吗? Shouldn't you be able to access the values via PHP as usual through $_POST['name_of_input_goes_here'] 你不应该像往常一样通过PHP访问这些值来通过$_POST['name_of_input_goes_here']

edit: you could always dump the contents of $_POST to see what you're receiving from the javascript form submission using print_r($_POST) . 编辑:您可以随时转储$ _POST的内容,以使用print_r($_POST)查看您从javascript表单提交中收到的内容。 That would give you some idea about what you'd need to do in PHP to access the data you need. 这可以让您了解在PHP中需要做什么来访问所需的数据。

Maybe it will help those who are looking:)也许它会帮助那些正在寻找的人:)

You send data like this:你发送这样的数据:

$.ajax({
    url: 'url_name',
    data: {
        form_data: $('#form').serialize(),

    },
    dataType: 'json',
    method: 'POST'
})

console.log($('#form').serialize()) //'f_ctrType=5&f_status=2&f_createdAt=2022/02/24&f_participants=1700'

Then on the server side use parse_str( $_POST['form_data'], $res ) .然后在服务器端使用parse_str( $_POST['form_data'], $res )

Then the variable $res will contain the following:然后变量$res将包含以下内容:

Array
( 
    [f_ctrType] => 5
    [f_status] => 2
    [f_createdAt] => '2022/02/24'
    [f_participants] => 1700
)

You can use this function in php to reverse serializeArray(). 你可以在php中使用这个函数来反转serializeArray()。

<?php
function serializeToArray($data){
        foreach ($data as $d) {
            if( substr($d["name"], -1) == "]" ){
                $d["name"] = explode("[", str_replace("]", "", $d["name"]));
                switch (sizeof($d["name"])) {
                    case 2:
                        $a[$d["name"][0]][$d["name"][1]] = $d["value"];
                    break;

                    case 3:
                        $a[$d["name"][0]][$d["name"][1]][$d["name"][2]] = $d["value"];
                    break;

                    case 4:
                        $a[$d["name"][0]][$d["name"][1]][$d["name"][2]][$d["name"][3]] = $d["value"];
                    break;
                }
            }else{
                $a[$d["name"]] = $d["value"];
            } // if
        } // foreach

        return $a;
    }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM