Возвращение JSON и HTML из PHP скрипт

Привет, я просмотрел здесь вопросы, но ничего не нашел. Я новичок в написании PHP и jQuery, так что несите меня.

То, что я пытаюсь сделать, это отправить запрос ajax с помощью jQuery на мой script, который запускает запрос mysql на данные из моей базы данных и сериализует его в формате JSON, используя php json_encode. Затем ответ обрабатывается с помощью доступного json2.js script. Все это прекрасно работает, но я также хотел бы вернуть больше данных, кроме JSON, из этого script.

в основном, я хотел бы также повторить следующую строку перед json_encode:

echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";

однако, мой jQuery оценивает весь ответ во время успеха ajax, из-за чего функция json.parse терпит неудачу из-за возврата script в недопустимый формат.

        success: function(data) {
            //retrieve comments to display on page by parsing them to a JSON object
            var obj = JSON.parse(data);
                    //loop through all items in the JSON array
                    for (var x = 0; x < obj.length; x++) {
                        //Create a container for the new element
                        var div = $("<div>").addClass("bubble").appendTo("#comments");
                        //Add author name and comment to container
                        var blockquote = $("<blockquote>").appendTo(div);
                            $("<p>").text(obj[x].comment).appendTo(blockquote);
                        var cite = $("<cite>").appendTo(div);
                            $("<strong>").text(obj[x].name).appendTo(cite);
                            $("<i>").text(obj[x].datetime).appendTo(cite);
                    }
                $("#db").attr("value", '' + initialComments + '');
    }   

Кто-нибудь знает, как я могу вернуть html-строку, а также json_encode, чтобы использовать этот script для большей, чем просто json-группы?

Благодарю, этот сайт был замечательным, отвечая на мои вопросы о нобе.

my php: `

    for ($x = 0, $numrows = mysql_num_rows($result); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($result);
    $comments[$x] = array("name" => stripslashes($row["name"]), "comment" => stripslashes($row["comment"]), "datetime" => date("m/d/Y g:i A", strtotime($comment['datetime'])));        
}

//echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";

$response = json_encode($comments);
echo $response;`

Ответы

Ответ 1

Не echo строка, сохраните ее в переменной. Построить простой массив $response = array( 'html' => $the_line_you_wanted_to_echo, 'jsobject' => $the_object_you_were_going_to_send_back ); и отправьте это обратно (через json_encode).

Кроме того, вам не нужен json2.js, jQuery имеет отличный парсер JSON.

вы можете загрузить как это $.get( 'your/url', { params : here }, success, 'JSON' );

Изменено в соответствии с вашей новой итерацией.

for ($x = 0, $num_rows = mysql_num_rows($result); $x < $num_rows; $x++) {
    $row = mysql_fetch_assoc($result);
    $comments[$x] = array(
        "name" => stripslashes($row["name"]), 
        "comment" => stripslashes($row["comment"]), 
        "datetime" => date("m/d/Y g:i A", strtotime($comment['datetime']))
    );        
}

$html = "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";

echo json_encode(array( 'comments' => $comments, 'html' => $html ));

то в вашем javascript у вас есть

function success( parsedObject ){
    parsedObject.html; // "<h1 style..."
    parsedObject.comments; // an array of objects
    parsedObject.comments[0].name 
    + " on " + parsedObject.comments[0].datetime 
    + " said \n" + parsedObject.comments[0].comment; // for example
}

Ответ 2

Как сказано выше, просто поместите все данные, которые вы хотите вернуть в массив, и закодируйте их.

<?php

echo json_encode(array(
    'html' => $html,
    'foo' => $bar,
    'bar' => $baz
));

?>

Также, как сказано, вам не нужен json2.js. Вы можете анализировать данные JSON с помощью любой из jQuery ajax-функций, указав тип данных как json.

$.ajax({
    type: 'POST',
    url: 'path/to/php/script.php',
    dataType: 'json',
    data: 'foo=bar&baz=whatever',
    success: function($data) {
        var html = $data.html;
        var foo = $data.foo;
        var bar = $data.bar;

        // Do whatever.
    }
});

РЕДАКТИРОВАТЬ. То, что сказала Хория. Единственный вариант, который я мог видеть, - это то, что вы хотите все в одном массиве.

Например:

PHP:

<?php

// You have your comment array sent up as you want as $comments
// Then just prepend the HTML string onto the beginning of your comments array.
// So now $comments[0] is your HTML string and everything past that is your comments.
$comments = array_unshift($comments, $your_html_string);

echo json_encode($comments);

?>

JQuery

$.ajax({
    type: 'POST',
    url: 'path/to/php/script.php',
    dataType: 'json',
    data: 'foo=bar&baz=whatever',
    success: function($comments) {
        // Here your html string.
        var html = $comments[0];

        // Make sure to start at 1 or you're going to get your HTML string twice.
        // You could also skip storing it above, start at 0, and add a bit to the for loop:
        // if x == 0 then print the HTML string else print comments.
        for (var x = 1; x < $comments.length; x++) {
            // Do what you want with your comments.
            // Accessed like so:
            var name = $comments[x].name;
            var comment = $comments[x].comment;
            var datetime = $comments[x].datetime;
        }
    }
});

Ответ 3

Вам может быть интересно jLinq, библиотека Javascript, которая позволяет вам запрашивать объекты Javascript. Пример запроса:

var results = jLinq.from(data.users)
    .startsWith("first", "a")
    .orEndsWith("y")
    .orderBy("admin", "age")
    .select();

jLinq поддерживает запрос вложенных объектов и выполнение соединений. Например:

var results = jLinq.from(data.users) 
    .join(data.locations, //the source array 
        "location", //the alias to use (when joined) 
        "locationId", // the location id for the user 
        "id" // the id for the location 
    ) 
    .select(function(r) { 
        return { 
            fullname:r.first + " " + r.last, 
            city:r.location.city, 
            state:r.location.state 
        }; 
    });