在解析JSON文件时,我得到了未定义

时间:2014-02-21 17:00:45

标签: jquery json web-services

我创建了一个php webservice。我试图使用Jquery解析JSON结果,但我总是得到这个错误:undefined 这是JSON结果:

{"posts":[{"post":{"user_id":"1","user_fullname":"taieb baccouch","user_email":"baccouch.taieb@gmail.com","user_password":"toto123","user_status":"1"}},{"post":{"user_id":"2","user_fullname":"zahra dagrir","user_email":"zahra@live.fr","user_password":"zahra123","user_status":"1"}}]}  

我的jquery代码:

<!DOCTYPE html>
<html>
    <head>
        <title>Web service</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
        </script>
        <script>
            $(document).ready(function() {
                $("button").click(function() {
                    $.getJSON("http://localhost/WebService/web-service.php?format=json", function(posts) {
                        $.each(posts, function(i, field) {
                            $("div").append(field.user_fullname + " ");
                        });

                    });
                });
            });
        </script>
    </head>
    <body>

        <button>Get JSON data</button>
        <div></div>

    </body>
</html>  

这是我的web-service.php代码:

<?php

$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default

/* connect to the db */
$link = mysql_connect('localhost', 'root', 'cabiat705') or die('Cannot connect to the DB');
mysql_select_db('webservice', $link) or die('Cannot select the DB');

/* grab the posts from the db */
$query = "SELECT * FROM users ";
$result = mysql_query($query, $link) or die('Error query:  ' . $query);

/* create one master array of the records */
$posts = array();
if (mysql_num_rows($result)) {
    while ($post = mysql_fetch_assoc($result)) {
        $posts[] = array('post' => $post);
    }
}

/* output in necessary format */
if ($format == 'json') {
    header('Content-type: application/json');
    echo json_encode(array('posts' => $posts));
} else {
    header('Content-type: text/xml');
    echo '<posts>';
    foreach ($posts as $index => $post) {
        if (is_array($post)) {
            foreach ($post as $key => $value) {
                echo '<', $key, '>';
                if (is_array($value)) {
                    foreach ($value as $tag => $val) {
                        echo '<', $tag, '>', htmlentities($val), '</', $tag, '>';
                    }
                }
                echo '</', $key, '>';
            }
        }
    }
    echo '</posts>';
}

/* disconnect from the db */
mysql_close($link);

我该如何解决?

1 个答案:

答案 0 :(得分:1)

试试这个:

$(document).ready(function () {
    $("button").click(function () {
        $.getJSON("http://localhost/WebService/web-service.php?format=json", function (posts) {
            $.each(posts.posts, function (i, field) {
                $("div").append(field.post.user_fullname + " ");
            });

        });
    });
});

<强> Fiddle Demo