如何将javascript数组发送到php? 我已经使用JSON.stringify到每个javascript数组并使用json_decode捕获数组,但stil不工作。
我不知道该怎么做了。有什么建议吗?
在JS中:
jarak = new Array(koordinat_kapal_threat.length);
for (var i = 0; i < jarak.length; i++) {
jarak[i] = new Array(koordinat_kapal_threat.length);
for (var j = 0; j < jarak.length; j++) {
if (i === j) {
jarak[i][j] = 0;
} else {
var distance = getDistance(koordinat_kapal_threat[i], koordinat_kapal_threat[j]);
jarak[i][j] = distance;
}
}
}
// buat array visibilitas
visibilitas = new Array(koordinat_kapal_threat.length);
for (var i = 0; i < visibilitas.length; i++) {
visibilitas[i] = new Array(koordinat_kapal_threat.length);
for (var j = 0; j < visibilitas.length; j++) {
if (i === j) {
visibilitas[i][j] = 0;
} else {
var visibilitas_kapal = 1 / jarak[i][j];
visibilitas[i][j] = visibilitas_kapal;
}
}
}
var tau = 0.01;
// buat array feromon
feromon = new Array(koordinat_kapal_threat.length);
for (var i = 0; i < feromon.length; i++) {
feromon[i] = new Array(koordinat_kapal_threat.length);
for (var j = 0; j < feromon.length; j++) {
feromon[i][j] = tau;
}
}
var banyak_semut = koordinat_kapal_threat.length;
var a = JSON.stringify(koordinat_kapal_threat);
var b = JSON.stringify(jarak);
var c = JSON.stringify(visibilitas);
var d = JSON.stringify(feromon);
var data = {
koordinat_kapal_threat: a,
jarak: b,
visibilitas: c,
feromon: d,
banyak_semut: banyak_semut
};
$.ajax({
type: "POST",
dataType: "json",
url: "algoritmaAnt.php",
data: data,
success: function (result) {
var data = JSON.parse(result.responseText);
var jalur = new google.maps.Polyline({
path: data,
geodesic: true,
strokeColor: '#FCFF49', strokeOpacity: 1.0,
strokeWeight: 2,
});
jalur.setMap(map);
}
});
在PHP中:
$koordinat_kapal_threat =json_decode($_POST['koordinat_kapal_threat']);
$jarak = json_decode($_POST['jarak']);
$visibilitas =json_decode($_POST['visibilitas']);
$feromon = json_decode($_POST['feromon']);
$banyak_semut = $_POST['banyak_semut'];
答案 0 :(得分:0)
这是Simple Way,你需要使用JSON.stringify将Data编码为JSON,同样使用json_decode来提取数据
<强>的JavaScript 强> var a = JSON.stringify(your_array_name); var b = JSON.stringify(jarak); //你的数组
// Ajax Call
$.ajax({
type: "POST",
dataType: "json",
async:true,
url: "algoritmaAnt.php",
data: {'data1':a,'data2':b},
success: function (result) {
// your success operation;
}
});
PHP代码
$jarak = json_decode($_POST['data1']);
$data2 = json_decode($_POST['data2']);
print_r($jarak);
print_r($data2);
答案 1 :(得分:0)
无需对数组进行字符串化。将数据变更如下
var data = {
koordinat_kapal_threat: koordinat_kapal_threat,
jarak: jarak,
visibilitas: visibilitas,
feromon: feromon,
banyak_semut: banyak_semut
};