returning JSON and HTML from PHP script

前端 未结 3 590
清酒与你
清酒与你 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.

    <?php
    
    echo json_encode(array(
        'html' => $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:

    <?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'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;
            }
        }
    });
    
    0 讨论(0)
  • 2020-12-30 04:49

    You might be interested in jLinq, a Javascript library that allows you to query Javascript objects. A sample query would be:

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

    jLinq supports querying nested objects and performing joins. For example:

    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 
            }; 
        }); 
    
    0 讨论(0)
  • 2020-12-30 05:04

    Don't echo the line, save it in a variable. Construct a simple array $response = array( 'html' => $the_line_you_wanted_to_echo, 'jsobject' => $the_object_you_were_going_to_send_back ); and send that back ( via json_encode ) instead.

    Also, you don't need json2.js, jQuery has an excellent JSON parser.

    you can load like this $.get( 'your/url', { params : here }, success, 'JSON' );

    Changed to match your newly introduced iteration.

    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 ));
    

    then, in your javascript, you have

    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
    }
    
    0 讨论(0)
提交回复
热议问题