将数组从 JavaScript/jQuery 发送到 php
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5255533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending an array to php from JavaScript/jQuery
提问by FraserK
Possible Duplicate:
send arrays of data from php to javascript
I know there are many questions like this but I find that none of them are that clear.
我知道有很多这样的问题,但我发现没有一个是那么清楚。
I have an Ajax request like so:
我有一个像这样的 Ajax 请求:
$.ajax({
type: "POST",
url: "parse_array.php",
data: "array=" + array,
dataType: "json",
success: function(data) {
alert(data.reply);
}
});
How would I send a JavaScript array to a php file and what would be the php that parses it into a php array look like?
我将如何将 JavaScript 数组发送到 php 文件,将其解析为 php 数组的 php 是什么样的?
I am using JSON.
我正在使用 JSON。
回答by Jason
Step 1
步骤1
$.ajax({
type: "POST",
url: "parse_array.php",
data:{ array : JSON.stringify(array) },
dataType: "json",
success: function(data) {
alert(data.reply);
}
});
Step 2
第2步
You php file looks like this:
您的 php 文件如下所示:
<?php
$array = json_decode($_POST['array']);
print_r($array); //for debugging purposes only
$response = array();
if(isset($array[$blah]))
$response['reply']="Success";
else
$response['reply']="Failure";
echo json_encode($response);
Step 3
第 3 步
The success function
成功函数
success: function(data) {
console.log(data.reply);
alert(data.reply);
}
回答by coldfix
You can just pass a javascript object.
您可以只传递一个 javascript 对象。
JS:
JS:
var array = [1,2,3];
$.ajax({
type: "POST",
url: "parse_array.php",
data: {"myarray": array, 'anotherarray': array2},
dataType: "json",
success: function(data) {
alert(data.reply); // displays '1' with PHP from below
}
});
On the php side you need to print JSON code:
在 php 端,您需要打印 JSON 代码:
PHP:
PHP:
$array = $_POST['myarray'];
print '{"reply": 1}';
回答by diEcho
HI,
你好,
use json_encode()on parse_array.php
json_encode()在parse_array.php 上使用
and retrive data with json_decode()
并检索数据 json_decode()

