传递一个JS数组到PHP [英] Passing a js array to PHP

查看:107
本文介绍了传递一个JS数组到PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过$ _ 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​​);

        }


?>
 

解决方案

您应该序列化数组转换成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

这篇关于传递一个JS数组到PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆