我正在尝试使用ajax post方法将数组从.js文件传递到PHP页面。您能帮助我了解为什么它不起作用吗?
//js file
$.ajax({
type: "POST",
url: "http://localhost/Project_part3/includes/graph.php",
datatype: 'JSON',
data: {'data1' : JSON.stringify(data1)},
success: function(data){
console.log("success:", data1);
},
failure: function(errMsg) {
console.error("error:",errMsg);
}
});
//PHP page
<?php
$data1 = json_encode($_POST["data1"]);
var_dump ($_POST["data1"]);
?>
答案 0 :(得分:1)
如果您的JS中的data1
数组已经是一个javascript数组,则无需执行JSON.stringify()
,因为这会将它变成字符串。
您现在就可以开始data: data1
var data1 = {
yourKey1: "yourValue",
yourKey2: "moreStuff"
};
$.ajax({
type: "POST",
url: "http://localhost/Project_part3/includes/graph.php",
datatype: 'JSON',
data: data1,
success: function(data){
console.log("success:", data1);
},
failure: function(errMsg) {
console.error("error:",errMsg);
}
});