2010-01-17 79 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 
     }; 
    });