При разборе файла JSON я получаю неопределенный

0

Я создал веб-сервис php. Я пытаюсь разобрать результат JSON с помощью Jquery, но всегда получаю эту ошибку: undefined.
Вот результат JSON:

{"posts":[{"post":{"user_id":"1","user_fullname":"taieb baccouch","user_email":"[email protected]","user_password":"toto123","user_status":"1"}},{"post":{"user_id":"2","user_fullname":"zahra dagrir","user_email":"[email protected]","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);

Как я могу это исправить?

  • 0
    Вы уверены, что не делаете междоменный запрос?
  • 0
    @A.WolffA.Wolff Я обновил свой код. Пожалуйста, взгляните
Теги:
web-services

1 ответ

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 + " ");
            });

        });
    });
});

Демо-версия скрипта

Ещё вопросы

Сообщество Overcoder
Наверх
Меню