2010-01-17 58 views
14

Ciao ho cercato tra le domande qui, ma non ho trovato nulla. Sono nuovo nello scrivere PHP e jQuery, quindi abbi pazienza con me.restituendo JSON e HTML dallo script PHP

Quello che sto cercando di fare è inviare una richiesta Ajax utilizzando jQuery al mio script che esegue una query mysql sui dati dal mio database e la serializza nel formato JSON utilizzando php json_encode. La risposta viene quindi analizzata con lo script json2.js disponibile. Tutto questo funziona bene, ma mi piacerebbe anche restituire più dati diversi da JSON solo da questo script.

principalmente, mi piacerebbe eco anche la seguente riga prima json_encode:

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

tuttavia, il mio jQuery sta valutando l'intera risposta durante il successo ajax, rendendo la funzione JSON.parse sicuro a causa il ritorno dello script è in un formato non valido.

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

Qualcuno sa come posso restituire la linea html così come la json_encode per utilizzare questo script per più di popolazione di poco JSON?

grazie, questo sito è stato meraviglioso nel rispondere alle mie domande noob.

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

risposta

19

Non echo la linea, salvarlo in una variabile. Costruisci un semplice array $response = array( 'html' => $the_line_you_wanted_to_echo, 'jsobject' => $the_object_you_were_going_to_send_back ); e rimandalo indietro (tramite json_encode).

Inoltre, non è necessario json2.js, jQuery ha un eccellente parser JSON.

è possibile caricare in questo modo $.get('your/url', { params : here }, success, 'JSON');

cambiato per abbinare il vostro iterazione di nuova introduzione.

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

poi, nel vostro javascript, devi

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

grazie per la risposta, ma io non sono sicuro di come implementare, perché ho solo bisogno di eco il codice HTML una volta in contrasto con il ciclo for ho creato per i commenti. puoi dare un'occhiata al mio codice aggiunto alla domanda e indicarmi la giusta direzione? Grazie! –

+0

Se dai un'occhiata alla mia risposta puoi fare la stessa cosa solo senza usare un array. Quindi "echo json_encode ($ html);" e poi nella funzione di successo si dovrebbe semplicemente accedervi tramite '$ dati'. – anomareh

+0

grazie! l'array json_encode era proprio quello di cui avevo bisogno. –

5

Come detto sopra appena messo tutti i dati che si desidera tornare in un array e codificare questo.

<?php 

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

?> 

Inoltre come detto non è necessario json2.js. È possibile analizzare i dati JSON con una qualsiasi delle funzioni ajax di jQuery specificando il tipo di dati come 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 Più o meno quello che Horia detto. L'unica altra variazione che potrei vedere è se volessi tutto nello stesso array.

Ad esempio:

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

grazie per la risposta: l'ho fatto, ma ora l'html viene ripetuto per ogni voce nel mio database a causa del fatto che l'array è coinvolto in un ciclo for. c'è un modo in cui posso combinare la matrice di informazioni dal db con la singola variabile html per produrre json che visualizza solo il codice html: una volta? –

+0

Ho aggiornato la mia risposta per quello che stavi cercando. – anomareh

0

Potreste essere interessati a jLinq, una libreria JavaScript che permette di interrogare oggetti JavaScript. Una query di esempio potrebbe essere:

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

jLinq supporta l'interrogazione di oggetti nidificati e l'esecuzione si unisce. Per esempio:

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 
     }; 
    }); 
Problemi correlati