您可以使用JSON 在 PHP 和 JavaScript 之间进行通信(查找 PHP json_encode 和 json_decode 函数),它将允许您在语言之间几乎原生地传递复杂的数组。
编辑:几个例子来说明它是如何工作的,我在这里使用 jQuery 作为我的例子
通过 AJAX 从 PHP 脚本请求信息:
$.ajax({
method: 'GET',
dataType: 'json',
success: function(data) {
for (i in data.messages) {
output(data.messages[i]);
}
}
});
var output = function(message) {
console.log(message.id);
console.log(message.sender.id);
};
PHP脚本可以输出:
$messages = array(
array(
'id' => 1,
'message' => 'Awesome',
'sender' => array(
'id' => 1, 'name' => 'John',
),
),
);
echo json_encode(array('messages' => $messages));
通过 AJAX 使用 JSON 发送信息:
// Example data object, you can have this infinitely nested
var data = [
{id: 1, "message": "test" }
];
$.ajax({
method: 'POST',
dataType: 'json',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
});
var output = function(message) {
console.log(message.id);
console.log(message.sender.id);
};
然后 PHP 脚本可以使用:
$data = json_decode(file_get_contents('php://input'), true);
// This becomes a simple 2D PHP array which is an exact representation as your JS object. The above example data can be output as:
foreach ($data as $message) {
echo $message['id'] . ' - ' .$message['message'];
}