如何从 PHP 中的 serializeArray 获取 POST 值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2237601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the POST values from serializeArray in PHP?
提问by Richard
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
谢谢,理查德
回答by Gordon
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 $datadoes 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 arrayof objects, ready to be encodedas 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.jsas 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作为 3rd 方库,要么使用http://api.jquery.com/序列化/代替。
回答by Clark Burns
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
回答by Sarfraz
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
http://www.tutorialspoint.com/jquery/ajax-serializearray.htm
回答by Shinto Anto
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] => [email protected] ) [3] => Array ( [name] => phone [value] => 048028 ) [4] => Array ( [name] => titles [value] => Enquiry ) [5] => Array ( [name] => text [value] => test ) )
回答by Seymore Throttle
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()方法,因为它可能会产生不需要的输出。
回答by Ty W
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 不会改变发布值的方式吗?您不应该像往常一样通过 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). 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). 这将使您了解需要在 PHP 中执行哪些操作才能访问所需的数据。
回答by Adriano de Abreu Wanderley
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;
}
?>

