使用 Ajax 将数组发送到 PHP 脚本
我有由函数 .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;
}
最好的方法是什么?
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:
$data = $_POST['data'];
// here i would like use foreach:
foreach($data as $d){
echo $d;
}
How is the best way for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将数据字符串编码为 JSON。
在 PHP 中
注意
当您通过 POST 发送数据时,它需要作为键值对。
因此
data: dataString
是错误的。相反,执行:
data: {data:dataString}
Encode your data string into JSON.
In your PHP
Note
When you send data via POST, it needs to be as a keyvalue pair.
Thus
data: dataString
is wrong. Instead do:
data: {data:dataString}
http://api.jquery.com/serializeArray/
http://api.jquery.com/serializeArray/
jQuery
ajax()
函数中的数据接受匿名对象作为其输入,请参阅文档< /a>.因此,您正在寻找的示例是:您也可以自己编写 POST/GET 查询,例如
key=val&key2=val2
,但您必须自己处理转义,即不切实际的。Data in jQuery
ajax()
function accepts anonymous objects as its input, see documentation. So example of what you're looking for is:You may also write POST/GET query on your own, like
key=val&key2=val2
, but you'd have to handle escaping yourself which is impractical.如果您一直在尝试发送一维数组,并且 jquery 将其转换为逗号分隔值 >:(,则按照下面的代码操作,将提交实际的数组到
php
而不是所有逗号分隔的 bull**it假设您必须附加一个名为
myvals
的维度数组。你这样做
你会得到..
请原谅我语言,但是有很多 Rube-Goldberg 解决方案散布在网络上,特别是在所以,但它们都不是优雅的,也不能解决通过ajax post实际将一维数组发送到
php
的问题。If you have been trying to send a one dimentional array and jquery was converting it to comma separated values >:( then follow the code below and an actual array will be submitted to
php
and not all the comma separated bull**it.Say you have to attach a single dimentional array named
myvals
.Now inside
php
when you do thisYou will get ..
Pardon my language, but there are hell lot of Rube-Goldberg solutions scattered all over the web and specially on SO, but none of them are elegant or solve the problem of actually posting a one dimensional array to
php
via ajax post. Don't forget to spread this solution.dataString 建议数据采用字符串格式(并且可能由字符分隔)。
如果 dataString 不是字符串而是数组(您的问题表明),请使用 JSON。
dataString suggests the data is formatted in a string (and maybe delimted by a character).
if dataString is not a string but infact an array (what your question indicates) use JSON.