简体   繁体   English

将数组值从 javascript 代码传递给 php

[英]Pass the array values from javascript code to php

I'm trying to pass the values of array to php but i can not get the values.我正在尝试将数组的值传递给 php,但我无法获取这些值。 It returns NULL, when I use var_dump() it returns array(1) { [0]=> string(0) "" } Array ( [0] => )它返回 NULL,当我使用 var_dump() 时它返回 array(1) { [0]=> string(0) "" } Array ( [0] => )

Here the code:这里的代码:

$("#submit").click(function () {
   var newhour= [];
   for (var i = 0; i < arrayNumbers.length; i++) {
        newhour.push(arrayNumbers[i].toString().split(','));   
        console.log("each: " + newhour[i]); // output: each: 07:00,08:30
                                                       each: 18:00,19:00                                                   
   }
   console.log("all: " + newhour); //output: all: 07:00,08:30,18:00,19:00

   var jsonx = JSON.stringify(newhour);
   console.log("x: " +jsonx); // output: x: [["07:00","08:30"],["18:00","19:00"]]
   $.ajax({
         type: "POST",
         url: "hour.php",
         data:{data: jsonx}, 
         cache: false,
         success: function(){
                  alert("OK");
         }
   });
});

hour.php file include: hour.php 文件包括:

  $data = json_decode($_POST['data'],true);
//$data = json_decode(($_POST['data']));  
//$data = explode(",", $_POST['data']);
//$data = $_POST['data']; 
  echo "data: " .$data;
  var_dump($data);
  foreach($data as $d){
        echo $d;
  }

I struggled with that for hours, i tried everything but couldn't get any values.我为此挣扎了几个小时,我尝试了一切,但无法获得任何值。 I don not understand where I'm wrong.我不明白我错在哪里。 Can you please help me with my code?你能帮我处理我的代码吗? Thanks in advance.提前致谢。

It works fine for me This is the data I used for arrayNumbers它对我来说很好用 这是我用于 arrayNumbers 的数据

var arrayNumbers = [1, 591, 283, 12];

This is the return data这是返回数据

data: Arrayarray(4) { [0]=> array(1) { [0]=> string(1) "1" } [1]=> array(1) { [0]=> string(3) "591" } [2]=> array(1) { [0]=> string(3) "283" } [3]=> array(1) { [0]=> string(2) "12" } } ArrayArrayArrayArray

EDIT : just tried a few different values for arrayNumbers.编辑:只是为arrayNumbers 尝试了几个不同的值。 When i used var arrayNumbers = [""];当我使用var arrayNumbers = [""]; I got your exact return.我得到了你的确切回报。 Check what values you are using for that because thats the issue.检查您为此使用了哪些值,因为这就是问题所在。

Note: I also had to comment out each: 18:00,19:00 , but I assumed you already had that commented and copied it wrong注意:我还必须注释掉each: 18:00,19:00 ,但我假设您已经注释掉并复制了错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM