PHP循环遍历jquery循环

时间:2014-09-30 17:51:25

标签: php jquery

我有这个简单的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。我不知道访问数组中值的正确方法。看来我做错了。

1 个答案:

答案 0 :(得分:2)

您误解了{}[]JavaScript之间的区别:

  1. {}是一个对象
  2. []是一个数组
  3. 在您的情况下,您应该传递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