douquan1015 2017-11-16 07:59 采纳率: 0%
浏览 91
已采纳

如何将javascript数组或JSON存储到php中

I have a javaScript array which I need to store in PHP so that later I can store it to MySQL database.

index.php

<form method="post">
<button type="submit" class="btn btn-default" id="php-submit" name="php-submit"><span class="glyphicon glyphicon-upload"></span></button>
<table class="table" id="table-1">
  <-- my finalArray gets generated by selecting some of these table cell values -->
</table>
</form>

app.js

$('#php-submit').click(function()
{   // For demo purpose, I have written hardcoded array values here
    var finalArray = ["Nov 2017 0:00 - 0:59", "Dec 2017 0:00 - 0:59", "Nov 2017 1:00 - 1:59", "Dec 2017 1:00 - 1:59"];
    // console.log(finalArray);
    str_json = JSON.stringify(finalArray);
    console.log(str_json);

    $.ajax({
      type: "POST",
      url: "script.php",
      data: {data : str_json}, 
      cache: false,
      success: function(){
        alert("OK");
      }
    });

    // $.post('script.php', { data: finalArray }, function (data) { 
    //  alert("OK");
    // });

});

After user clicks ('#php-submit') button, I want to be display 'finalArray' or 'str_json' on my script.php.

Below are 4 different approaches that I have tried.

script.php

// approach 1: output --> blank page

   $data = json_decode(stripslashes($_POST['data']));
   foreach($data as $d){
      echo $d;
   }

// approach 2: ouptut --> null

   $data = json_decode(stripslashes($_POST['data']));
   var_dump($data);

// approach 3: output --> null

   header('Content-type: application/json; charset=utf-8');
   $json = file_get_contents('php://input');
   $json_decode = json_decode($json, true); 
   $json_encode = json_encode($json_decode);
   echo $json_encode;

// approach 4: output --> array(1) { [0]=> string(4) "null" }

   $data = $_POST['data'];
   $json_encode = json_encode($data);
   $ar = explode(',', $json_encode);
   var_dump($ar);
  • 写回答

2条回答 默认 最新

  • dongniaoli1822 2017-11-16 08:12
    关注

    I believe the problem is that you are sending $.ajax request but are checking the script.php from browser tab. to see your ajax request you need to use Chrome Dev Tools. Like:

    1. Open Chrom Dev Tools with <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>I</kbd>
    2. Move to Network Tab. enter image description here
    3. Look for your request in the XHR section:enter image description here

    Now I ran your code and it worked just fine for me. As you can see from the screenshots too.

    Edit: Instead of sending an ajax request try submitting a dynaimcally generated <form>, Like:

    $('#php-submit').click(function()
    {
        var finalArray = ["Nov 2017 0:00 - 0:59", "Dec 2017 0:00 - 0:59", "Nov 2017 1:00 - 1:59", "Dec 2017 1:00 - 1:59"];
        str_json = JSON.stringify(finalArray);
    
            var newForm = $('<form>', {
                'action': 'script.php',
                'target': '_top',
                'method': 'POST'
            }).append($('<input>', {
                'name': 'data',
                'value': str_json,
                'type': 'hidden'
            }));
            $(document.body).append(newForm);
            newForm.submit();
    
    });
    

    But if you don't want to redirect to another page using <form>.Then in your script.php, do something like this using $_SESSION:

    if(isset($_POST['data']))
    {
        $_SESSION['data'] = json_decode(stripslashes($_POST['data']));
    }
    
    var_dump($_SESSION);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在虚拟机中安装flash code
  • ¥15 单片机stm32f10x编写光敏电阻调节3.3伏大功率灯亮度(光强越大灯越暗,白天正常光强灯不亮,使用ADC,PWM等模块)望各位找一下错误或者提供一个可实现功能的代码
  • ¥20 verilog状态机方法流水灯
  • ¥15 pandas代码实现不了意图
  • ¥15 GD32H7 从存储器到外设SPI传输数据无法重复启用DMA
  • ¥25 LT码在高斯信道下的误码率仿真
  • ¥45 渲染完成之后将物体的材质贴图改变,自动化进行这个操作
  • ¥15 yolov5目标检测并显示目标出现的时间或视频帧
  • ¥15 电视版的优酷可以设置电影连续播放吗?
  • ¥50 复现论文;matlab代码编写