2010-01-17 78 views
14

嗨在這裏通過問題搜索,但找不到任何東西。我在編寫PHP和jQuery方面很新,所以請耐心等待。從PHP腳本返回JSON和HTML

我想要做的是發送一個使用jQuery的ajax請求到我的腳本,該腳本對我的數據庫中的數據運行mysql查詢並使用php的json_encode將其序列化爲JSON格式。然後使用可用的json2.js腳本解析響應。所有這些工作都很好,但我還想從此腳本中返回除JSON之外的更多數據。

主要是,我想也呼應json_encode之前以下行:

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

然而,我的jQuery是評估阿賈克斯成功在整個響應,使得由於json.parse功能失效該腳本的返回格式無效。

 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使用這個腳本的不僅僅是JSON人口多嗎?

謝謝你,這個網站在回答我的noob問題方面一直很棒。

我的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;` 

回答

19

不要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 
} 
+0

感謝您的迴應,但我不知道如何實現它,因爲我只需要回聲一次的html,而不是我爲評論創建的for循環。你可以看看我添加到問題中的代碼並指向正確的方向嗎?謝謝! – 2010-01-18 00:08:53

+0

如果你看看我的答案,你可以做同樣的事情,而不使用數組。因此'echo json_encode($ html);'然後在成功函數中,您只需通過'$ data'訪問它。 – anomareh 2010-01-18 00:18:13

+0

謝謝! json_encode數組正是我所需要的。 – 2010-01-19 15:18:43

5

正如上面所說只是把所有你想回來的數組和編碼數據。

<?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'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

感謝您的答案 - 我做到了這一點,但現在由於數組參與for循環,我的數據庫中的每個條目都在迭代html。有沒有一種方法可以將來自數據庫的信息數組與單個html變量組合在一起,生成僅顯示html代碼的json? – 2010-01-18 01:09:15

+0

我更新了我的答案,以查找您要找的內容。 – anomareh 2010-01-18 12:22:22

0

您可能會感興趣的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 
     }; 
    });