【问题标题】:Passing an array of strings from JS to PHP将字符串数组从 JS 传递到 PHP
【发布时间】:2017-10-19 05:24:43
【问题描述】:

我在 JS 中有一个字符串数组,我想将它发送到 php(以便能够将它添加到 db)。这是我当前的代码-> 显示成功消息,但未显示 $_POST['array'] 变量。

请记住,我要发送的那个数组只有字符串值,称为times

JS

 function fetchDates(){
times = [];
var table = document.getElementById("timeScheduleBody");
var tableRows = table.getElementsByTagName("tr");
for(var j=0;j<tableRows.length;j++){
    var tableCells = tableRows[j].getElementsByTagName("td");
    for(var i = 0;i<tableCells.length;i++){
        if(tableCells[i].getAttribute('class').includes("success")){
            var arr = tableCells[i].getAttribute('value').split("-");
            var date, hour, mins;
            date = arr[0];
            hour = arr[1];
            mins = arr[2];
            times.push(date);
            times.push(hour);
            times.push(mins);
        }

    }
}
window.alert(times);

//send array to PHP from jQuery
jQuery.ajax({  
     type: "post",  
     url: window.location.href,  
     data: {array:times},
     success: function(){  
         alert("done"); 
     }  
}); 

}

PHP

<?php
if(isset($_POST['array'])){
$array = $_POST['array'];
echo $array[0];//just testing -> output: nothing
  foreach($array as $d){
     print '<script>window.alert($d);</script>';//also just to test -> output: nothing
  }
}
?>

【问题讨论】:

  • 你能补充一下times的定义位置和方式吗?
  • 将内容从 JavaScript 发送到 PHP(或其他后端)的简单方法是使用 JSON,使用 data: {array: JSON.stringify(times)} 发送,然后使用 $array = json_decode($_POST['array']); 在 PHP 中获取您的数组。
  • @insertusernamehere 我已经编辑了帖子。看看吧。

标签: javascript php jquery arrays


【解决方案1】:

但是您没有获取并显示 ajax 调用的响应,要查看响应,您必须在成功函数中获取响应...

PHP(test.php - 创建此文件并放在同一目录中):

<?php
if(isset($_POST['array']))
    print_r($_POST['array']);
?>

查询:

$.ajax({  
    type: 'POST',  
    url: 'test.php',  
    data: { array: times },
    success: function(response) {  
        alert(response); 
    }  
}); 

您将看到数组内容。您正在正确发送 javascript 数组,但是如果您想查看 ajax 调用的响应,您必须在成功函数中获取它并对其进行处理(提醒它,将其添加到 DOM 等)

【讨论】:

  • 它正在提醒整个 html :S
  • 等等...你在调用什么 php 文件?我已经编辑了答案。创建该 test.php 文件并测试 tha ajax 调用
  • @mickmackusa 我的意思是没有在成功函数中得到响应,所以没有显示它。我已经编辑了答案,试图更清楚
  • 我希望它将数据提供给同一页面。是否可以通过 Skype (mohammad_ghali) 给我打电话来帮助我。我真的很感激:)
猜你喜欢
  • 1970-01-01
  • 2013-05-15
  • 2015-10-29
  • 2016-10-26
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
相关资源
最近更新 更多