使用 Ajax 将数组发送到 PHP 脚本 [英] Send array with Ajax to PHP script
本文介绍了使用 Ajax 将数组发送到 PHP 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有由函数 .push 组成的数组.在数组中是非常大的数据.将它发送到 PHP 脚本的最佳方式是什么?
I have array made by function .push. In array is very large data. How is the best way send this to PHP script?
dataString = ??? ; // array?
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
cache: false,
success: function(){
alert("OK");
}
});
script.php:
script.php:
$data = $_POST['data'];
// here i would like use foreach:
foreach($data as $d){
echo $d;
}
最好的方法是什么?
推荐答案
将您的数据字符串编码为 JSON.
Encode your data string into 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 发送数据时,它需要作为一个键值对.
When you send data via POST, it needs to be as a keyvalue pair.
因此
数据:dataString
错了.而是这样做:
数据:{data:dataString}
这篇关于使用 Ajax 将数组发送到 PHP 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文