【问题标题】:returning JSON and HTML from PHP script从 PHP 脚本返回 JSON 和 HTML
【发布时间】:2011-01-06 04:33:21
【问题描述】:

您好在这里搜索了问题,但找不到任何东西。我是编写 PHP 和 jQuery 的新手,所以请耐心等待。

我要做的是使用 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 在 ajax 成功期间评估整个响应,导致 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 填充?

谢谢,这个网站很好地回答了我的菜鸟问题。

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

【问题讨论】:

    标签: php jquery html json


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回复,但我不确定如何实现它,因为我只需要回显一次 html,而不是为 cmets 创建的 for 循环。你能看看我添加到问题中的代码并指出我正确的方向吗?谢谢!
    • 如果你看看我的回答,你可以在不使用数组的情况下做同样的事情。所以echo json_encode($html); 然后在成功函数中你只需通过$data 访问它。
    • 如何处理 jQuery 添加到 HTML 字符串中的斜线?
    • 那很可能不是 jQuery,而是你的 PHP/Apache。
    【解决方案2】:

    您可能对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 
            }; 
        }); 
    

    【讨论】:

      【解决方案3】:

      如上所述,只需将您想要返回的所有数据放入一个数组中并对其进行编码。

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

      【讨论】:

      • 感谢您的回答 - 我这样做了,但现在由于数组涉及 for 循环,因此我的数据库中的每个条目都在迭代 html。有没有一种方法可以将数据库中的信息数组与单个 html 变量结合起来生成只显示 html: 代码一次的 json?
      猜你喜欢
      • 2015-10-18
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      相关资源
      最近更新 更多