【发布时间】: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