我有这个简单的jQuery函数:
$(document).ready(function () {
var books = {};
books.id = '1';
books.author = 'Bob';
$.post('/index.php',
{
books: books
},
function(data, textStatus)
{
alert(data);
});
});
这个index
PHP脚本:
<?php
foreach($_POST['books'] AS $key) {
echo ''.$key['id'].' is written by '.$key['author'].'';
}
?>
我想遍历jQuery数组并显示数组中每个键的id和author。我不知道访问数组中值的正确方法。看来我做错了。
答案 0 :(得分:2)
您误解了{}
中[]
与JavaScript
之间的区别:
{}
是一个对象[]
是一个数组在您的情况下,您应该传递array
本书objects
,以便在您的php脚本中使用。
例如:
var books = [
{
id: 1,
name: "The Da Vinci Code",
author: "Dan Brown"
},
{
id: 1,
name: "Gray Mountain: A Novel",
author: "John Grisham"
}
]
要在数组初始化后向数组中添加更多元素,只需使用push
:
books.push({id: 3, name: "Avatar", author: "Lisa Fitzpatrick"});
将输出:
1 is written by Dan Brown
2 is written by John Grisham
3 is written by Lisa Fitzpatrick