returning JSON and HTML from PHP script

前端 未结 3 608
清酒与你
清酒与你 2020-12-30 04:14

Hi searched through the questions here, but couldn\'t find anything. I\'m new at writing PHP and jQuery, so bear with me.

What I\'m trying to do is send an ajax requ

3条回答
  •  借酒劲吻你
    2020-12-30 04:41

    As said above just put all the data you want to get back in an array and encode that.

     $html,
        'foo' => $bar,
        'bar' => $baz
    ));
    
    ?>
    

    Also as said you don't need json2.js. You can parse JSON data with any of jQuery's ajax functions by specifying the data type as 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.
        }
    });
    

    EDIT Pretty much what Horia said. The only other variation I could see is if you wanted everything in the same array.

    For example:

    PHP:

    
    

    jQuery:

    $.ajax({
        type: 'POST',
        url: 'path/to/php/script.php',
        dataType: 'json',
        data: 'foo=bar&baz=whatever',
        success: function($comments) {
            // Here's 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;
            }
        }
    });
    

提交回复
热议问题