传递一个JS数组到PHP数组、JS、PHP

由网友(动人的温柔ゝ)分享简介:通过$ _ POST 我为什么不能访问我的数组中的PHP?我试图使用jQuery的$。员额法。下面是更正后的code与您的建议:我的javascript:<脚本类型=文/ JavaScript的>VAR selectedValues​​;VAR serializedValues​​;$(TD)。点击(...通过$ _ POST

我为什么不能访问我的数组中的PHP?我试图使用jQuery的$。员额法。下面是更正后的code与您的建议:

我的javascript:

 <脚本类型=文/ JavaScript的>
VAR selectedValues​​;
VAR serializedValues​​;
$(TD)。点击(函数(){
$(本).toggleClass('selectedBox');

//地图TDS的文字selectedValues
selectedValues​​ = $ .MAP($(td.selectedBox),功能(OBJ){
        返回$(物镜)的.text();

});

serializedValues​​ = JSON.stringify(selectedValues​​);

// $。员额('/ URL /到/页',{'someKeyName:VARIABLENAME}); //为例
.post的$('handler.php',
      {'serializedValues​​:serializedValues​​},
      功能(数据){
        //调试
     }
);

});

< / SCRIPT>
 

我的PHP:

 < PHP
如果(使用isset($ _ POST ['serializedValues​​'])){

            后续代码var_dump($ _ POST ['serializedValues​​']);
            $ originalValues​​ = json_de code($ _ POST ['serializedValues​​'],1);
            的print_r($ originalValues​​);

        }


?>
 

解决方案 js如何获取php页面数组里面的值

您应该序列化数组转换成JSON字符串:

  serializedValues​​ = JSON.stringify(selectedValues​​)
 

和它传递给PHP。然后去code与json_de code:

  $ originalValues​​ = json_de code($ _ POST ['serializedValues​​'],1);
 

http://php.net/manual/ru/ function.json德code.php

Why can't I access my array through $_POST in PHP? I'm trying to use the jQuery $.post method. Here is the corrected code with your suggestions:

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

My php:

<?php
if(isset($_POST['serializedValues'])) {

            var_dump($_POST['serializedValues']);
            $originalValues = json_decode($_POST['serializedValues'], 1);
            print_r($originalValues);

        }


?>

解决方案

You should serialize your array into json string:

serializedValues = JSON.stringify(selectedValues)

And pass it to php. And then decode with json_decode:

$originalValues = json_decode($_POST['serializedValues'], 1);

http://php.net/manual/ru/function.json-decode.php

阅读全文

相关推荐

最新文章