为什么我不能通过 PHP 中的 $_POST 访问我的数组?我正在尝试使用 jQuery $.post 方法。以下是包含您的建议的更正代码:
我的JavaScript:
<script type="text/javascript">
var selectedValues;
var serializedValues;
$("td").click(function() {
$(this).toggleClass('selectedBox');
// map text of tds to selectedValues
selectedValues = $.map($("td.selectedBox"), function(obj) {
return $(obj).text();
});
serializedValues = JSON.stringify(selectedValues);
// $.post('/url/to/page', {'someKeyName': variableName}); //exemple
$.post('handler.php',
{'serializedValues' : serializedValues},
function(data) {
//debug
}
);
});
</script>
我的php:
<?php
if(isset($_POST['serializedValues'])) {
var_dump($_POST['serializedValues']);
$originalValues = json_decode($_POST['serializedValues'], 1);
print_r($originalValues);
}
?>
你应该将数组序列化为 json 字符串:
serializedValues = JSON.stringify(selectedValues)
并将其传递给 php。然后用json_decode解码:
$originalValues = json_decode($_POST['serializedValues'], 1);
http://php.net/manual/ru/function.json-decode.php
附带说明一下;你的javascript可以重构成更简单的东西。
$("td").click(function() {
$(this).toggleClass('selectedBox');
// map text of tds to selectedValues
var selectedValues = $.map($("td.selectedBox"), function(obj) {
return $(obj).text();
});
// $.post('/url/to/page', {'someKeyName': variableName}); //exemple
$.post('handler.php',
{'serializedValues' : JSON.stringify(serializedValues)},
function(data) {
//debug
}
);
});