2010-01-17 18 views
14

Hola busqué las preguntas aquí, pero no pude encontrar nada. Soy nuevo al escribir PHP y jQuery, así que tengan paciencia conmigo.devolviendo JSON y HTML desde el script PHP

Lo que estoy tratando de hacer es enviar una solicitud ajax utilizando jQuery a mi script que ejecuta una consulta mysql en datos de mi base de datos y la serializa en el formato JSON usando json_encode de php. La respuesta se analiza con el script json2.js disponible. Todo esto funciona bien, pero también me gustaría devolver más datos que no sean solo JSON de este script.

sobre todo, me gustaría también eco de la línea siguiente antes del json_encode:

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

sin embargo, mi jQuery está evaluando la respuesta completa durante el éxito del Ajax, por lo que la función JSON.parse fallan debido a la vuelta del script está en un formato inválido.

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

¿alguien sabe cómo puedo devolver la línea de HTML, así como la json_encode utilizar este script desde hace más de población de poco JSON?

gracias, este sitio web ha sido maravilloso al responder mis preguntas de novato.

mi 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;` 

Respuesta

19

Do not echo la línea, guardarlo en una variable. Construya una matriz simple $response = array( 'html' => $the_line_you_wanted_to_echo, 'jsobject' => $the_object_you_were_going_to_send_back ); y envíela de vuelta (a través de json_encode).

Además, no necesita json2.js, jQuery tiene un excelente analizador JSON.

que es posible cargar como esto $.get('your/url', { params : here }, success, 'JSON');

modificado para acomodarse a su iteración de reciente introducción.

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

entonces, en su javascript, tienes

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

gracias por la respuesta, pero no estoy seguro de cómo implementarlo porque solo necesito repetir el html una vez en contraposición al ciclo for creado para los comentarios. ¿Puedes echarle un vistazo a mi código, añadirlo a la pregunta y señalarme en la dirección correcta? ¡Gracias! –

+0

Si miras mi respuesta, puedes hacer lo mismo sin usar una matriz. Entonces 'echo json_encode ($ html);' y luego en la función de éxito, solo accederá a través de '$ data'. – anomareh

+0

gracias! la matriz json_encode era justo lo que necesitaba. –

5

Como se ha dicho más arriba sólo hay que poner todos los datos que desea volver a entrar en una matriz y codificar eso.

<?php 

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

?> 

También como he dicho, no necesita json2.js. Puede analizar datos JSON con cualquiera de las funciones ajax de jQuery especificando el tipo de datos como 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. 
    } 
}); 

EDITAR Más o menos lo que dijo Horia. La única otra variación que podría ver es si querías todo en la misma matriz.

Por ejemplo:

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

gracias por la respuesta: hice esto, pero ahora el html se repite para cada entrada en mi base de datos debido a que la matriz está involucrada en un bucle for. ¿Hay alguna manera en que pueda combinar la matriz de información de la base de datos con la única variable html para producir json que solo muestre el código html: una vez? –

+0

Actualicé mi respuesta para lo que estabas buscando. – anomareh

0

Usted puede estar interesado en jLinq, una biblioteca de Javascript que permite consultar los objetos de Javascript. Una consulta de muestra sería:

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

jLinq admite consultar objetos anidados y realizar uniones. Por ejemplo:

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 
     }; 
    }); 
Cuestiones relacionadas