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

时间:2023-01-05 13:36:09

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

7 个解决方案

#1


4  

Like Gumbo suggested, you are likely not processing the return value of json_decode.
Try

像Gumbo建议的那样,您可能无法处理json_decode的返回值。尝试

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

If $data does not contain the expected data, then var_dump($_POST); to see what the Ajax call did post to your script. Might be you are trying to access the JSON from the wrong key.

如果$ data不包含预期数据,则var_dump($ _ POST);查看Ajax调用发布到您的脚本的内容。您可能正在尝试从错误的密钥访问JSON。

EDIT
Actually, you should make sure that you are really sending JSON in the first place :)
The jQuery docs for serialize state The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Ready to be encoded is not 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.

编辑实际上,你应该确保你真的首先发送JSON :)用于序列化状态的jQuery文档.serializeArray()方法创建一个JavaScript对象数组,准备编码为JSON字符串。准备编码不是JSON。显然,jQuery中没有Object2JSON函数,所以要么使用https://github.com/douglascrockford/JSON-js/blob/master/json2.js作为第三方库,要么使用http://api.jquery.com/序列化/而不是。

#2


4  

The JSON structure returned is not a string. You must use a plugin or third-party library to "stringify" it. See this for more info:

返回的JSON结构不是字符串。您必须使用插件或第三方库来“字符串化”它。有关详细信息,请参阅此

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

#3


4  

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

#4


3  

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

#5


1  

I have a very similar situation to this and I believe that Ty W has the correct answer. 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.

我有一个非常类似的情况,我相信Ty W有正确的答案。我将包含一个我的代码示例,以防万一有足够的差异来改变结果,但似乎你可以像在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()方法,因为它可能会产生不需要的输出。

#6


0  

the javascript doesn't change the way that the values get posted does it? Shouldn't you be able to access the values via PHP as usual through $_POST['name_of_input_goes_here']

javascript不会改变值发布的方式吗?通过$ _POST ['name_of_input_goes_here']你不应该像往常一样通过PHP访问这些值

edit: you could always dump the contents of $_POST to see what you're receiving from the javascript form submission using print_r($_POST). That would give you some idea about what you'd need to do in PHP to access the data you need.

编辑:您可以随时转储$ _POST的内容,以使用print_r($ _ POST)查看您从javascript表单提交中收到的内容。这可以让您了解在PHP中需要做什么来访问所需的数据。

#7


0  

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;
    }
?>

#1


4  

Like Gumbo suggested, you are likely not processing the return value of json_decode.
Try

像Gumbo建议的那样,您可能无法处理json_decode的返回值。尝试

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

If $data does not contain the expected data, then var_dump($_POST); to see what the Ajax call did post to your script. Might be you are trying to access the JSON from the wrong key.

如果$ data不包含预期数据,则var_dump($ _ POST);查看Ajax调用发布到您的脚本的内容。您可能正在尝试从错误的密钥访问JSON。

EDIT
Actually, you should make sure that you are really sending JSON in the first place :)
The jQuery docs for serialize state The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Ready to be encoded is not 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.

编辑实际上,你应该确保你真的首先发送JSON :)用于序列化状态的jQuery文档.serializeArray()方法创建一个JavaScript对象数组,准备编码为JSON字符串。准备编码不是JSON。显然,jQuery中没有Object2JSON函数,所以要么使用https://github.com/douglascrockford/JSON-js/blob/master/json2.js作为第三方库,要么使用http://api.jquery.com/序列化/而不是。

#2


4  

The JSON structure returned is not a string. You must use a plugin or third-party library to "stringify" it. See this for more info:

返回的JSON结构不是字符串。您必须使用插件或第三方库来“字符串化”它。有关详细信息,请参阅此

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

#3


4  

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

#4


3  

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

#5


1  

I have a very similar situation to this and I believe that Ty W has the correct answer. 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.

我有一个非常类似的情况,我相信Ty W有正确的答案。我将包含一个我的代码示例,以防万一有足够的差异来改变结果,但似乎你可以像在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()方法,因为它可能会产生不需要的输出。

#6


0  

the javascript doesn't change the way that the values get posted does it? Shouldn't you be able to access the values via PHP as usual through $_POST['name_of_input_goes_here']

javascript不会改变值发布的方式吗?通过$ _POST ['name_of_input_goes_here']你不应该像往常一样通过PHP访问这些值

edit: you could always dump the contents of $_POST to see what you're receiving from the javascript form submission using print_r($_POST). That would give you some idea about what you'd need to do in PHP to access the data you need.

编辑:您可以随时转储$ _POST的内容,以使用print_r($ _ POST)查看您从javascript表单提交中收到的内容。这可以让您了解在PHP中需要做什么来访问所需的数据。

#7


0  

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;
    }
?>