gpt4 book ai didi

php - 使用ajax将JavaScript数组传输到PHP数组?

转载 作者:行者123 更新时间:2023-11-28 13:47:26 26 4
gpt4 key购买 nike

我正在尝试将数据列表从 javascript 数组传输到 php 数组,但我似乎无法让 ajax 来完成此任务。有人可以告诉我如何执行此操作的代码吗?到目前为止,这就是我所拥有的,这只是数组:

JAVASCRIPT
var dates;
// the dates array is then filled up here
// it contains information in the form {'2012-01-01', '2012-03-12', ...}

$.ajax({
type: "REQUEST",
url: "NAMEOFPHPFILE.php",
data: { sendData1 : dates },
success: function() {
alert("Attempting to transfer array -> AJAX");
}
});

var submissions;
// the submissions array is then filled up here
// it contains information in the form {int, int, ...}

// ect ......... with 3 more arrays using { sendData2 : submissions },
PHP
<?php
$bDates = $_REQUEST['sendData1'];
// need to set this array = to the JavaScript dates array
$bSubmissions = $_REQUEST['sendData2'];
// need to set this array = to the JavaScript submissions array
?>

我更愿意使用 REQUEST 方法来阻止信息登录到 URL。 当尝试使用 POST 而不是 REQUEST 时,此代码也不起作用

在 .php 页面的最后,我将一堆数组输出到 CSV 页面,在其中迭代数组并将它们的元素放入文件中。这已经可以工作了,但是我需要将其中一些数组从 javascript 传输到 PHP,以便我可以吐出数据。看起来像这样:

<?php


$stringData = "Dates, Number of Lines Changed, , Bug Dates, Arrivals, Fixed, Closed, Hold_";
for($i = 0; $i < sizeof($dataXAxis); $i++){
$date = substr($_REQUEST['Dates'][$i+1], 0, 24);
$stringData .= "$date, $dataYAxis[$i], , $bDates[$i], $bSubmissions[$i], $bCompletions[$i], $bDones[$i], $bRejections[$i]_";
}


echo '<BR><BR><a href="download_csv.php?csv=' . $stringData . '" target="_blank">Download Your CSV File</a>';
?>

为什么 AJAX 不起作用?数组显示为空...

最佳答案

一种方法是尝试以 JSON 形式发送数据。然后使用json_decode,可以将其转换为数组。示例:

   var Json = {"User1":"John", "User2":"Joe", "User3","Jerry"};
var data = "data="+Json;
hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
console.log(hr.responseText);
}
}
hr.open("POST", "parsefile.php", true);
hr.send(data);

然后,当您获取 PHP 文件中的数据时,它类似于:

 $data = $_POST['data'];
$array = json_decode($data, true);

这一切都会告诉 php 将我们的数据转换为关联数组。然后可以将其作为关联数组进行操作。

关于php - 使用ajax将JavaScript数组传输到PHP数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13204457/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com