我有一个由函数 .push 创建的数组。在数组中是非常大的数据。将其发送到 PHP 脚本的最佳方式是什么?
dataString = ??? ; // array?
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
cache: false,
success: function(){
alert("OK");
}
});
script.php:
$data = $_POST['data'];
// here i would like use foreach:
foreach($data as $d){
echo $d;
}
最好的方法是什么?
最佳答案
将您的数据字符串编码为 JSON。
dataString = ??? ; // array?
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: {data : jsonString},
cache: false,
success: function(){
alert("OK");
}
});
在您的 PHP 中
$data = json_decode(stripslashes($_POST['data']));
// here i would like use foreach:
foreach($data as $d){
echo $d;
}
注意
当您通过 POST 发送数据时,它需要作为键值对。
这样
数据:dataString
错了。而是这样做:
数据:{data:dataString}
关于php - 使用 Ajax 将数组发送到 PHP 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9001526/