用jquery从php文件中获取json数据

时间:2014-01-10 15:34:16

标签: javascript jquery ajax json

我已经看过关于此的所有答案,但它并没有帮助我。我正在尝试从PHP文件中获取json数据。它正在工作,但我无法输出所有数据。

我从PHP文件中获取的数组如下所示:

connected<pre>Array
(
[0] => Array
    (
        [CategoryID] => 1
        [CategoryName] => Beverages
        [Description] => Soft drinks, coffees, teas, beers, and ales
        [Picture] => beverages.gif
    )

[1] => Array
    (
        [CategoryID] => 2
        [CategoryName] => Condiments
        [Description] => Sweet and savory sauces, relishes, spreads, and seasonings
        [Picture] => condiments.gif
    )

[2] => Array
    (
        [CategoryID] => 3
        [CategoryName] => Confections
        [Description] => Desserts, candies, and sweet breads
        [Picture] => confections.gif
    )

[3] => Array
    (
        [CategoryID] => 4
        [CategoryName] => Dairy Products
        [Description] => Cheeses
        [Picture] => diary.gif
    )

[4] => Array
    (
        [CategoryID] => 5
        [CategoryName] => Grains/Cereals
        [Description] => Breads, crackers, pasta, and cereal
        [Picture] => cereals.gif
    )

[5] => Array
    (
        [CategoryID] => 6
        [CategoryName] => Meat/Poultry
        [Description] => Prepared meats
        [Picture] => meat.gif
    )

[6] => Array
    (
        [CategoryID] => 7
        [CategoryName] => Produce
        [Description] => Dried fruit and bean curd
        [Picture] => produce.gif
    )

[7] => Array
    (
        [CategoryID] => 8
        [CategoryName] => Seafood
        [Description] => Seaweed and fish
        [Picture] => seafood.gif
    )

 )
 </pre> 

我的Ajax函数如下所示:

$.ajax({
    url:"data.php",
    type:"json",
    success:function(data){
        console.log(data)
        $.each(data, function(key, field){
            $("container").append(field.CategoryName)
        })
    }
});

我收到了这个错误:

  

未捕获TypeError:无法使用'in'运算符在connectedArray中搜索'1678'

2 个答案:

答案 0 :(得分:0)

您的data.php应与此类似。

$arData = array(

    [0]=>array(

        'categoryID' => 1,
        'categoryName' => 'Beverages',
        'description' => 'oft drinks, coffees, teas, beers, and ales',
        'picture' => 'beverages.gif'      

    )

);

$jsonData = json_encode( $arData );
header( 'Content-Type: application/json' );
print( $jsonData );

答案 1 :(得分:0)

问题在于你的PHP输出,它不是有效的JSON,因为你有“连接”这个词和那里的HTML标签 - 将它们剥离出来,用json_encode对所有内容进行编码

然后添加

header('Content-type: application/json');

到文件的顶部。