【问题标题】:How to pass HTML with json and ajax如何使用 json 和 ajax 传递 HTML
【发布时间】:2016-09-01 19:26:42
【问题描述】:

我正在尝试使用 JSON 编码函数和 Ajax 显示数据库的输出。但是,我在如何传递 html 元素“”和 php“例如”方面遇到了困难。显示来自服务器的数据的变量。我希望使用 json 和 ajax 请求显示输出。谢谢。

这是我的代码

 //js
  function mpo() 
 {
     $.ajax({
         url: "main.php",
         cache: false,
         success: function(html){
             $("#show_div").html(html);
         }
     });
 }


//php

$bu = "<div class='main' style='margin-left:" .($level*60). "px'>";     
$bu = "<div class='main_one'>";
$bu = "<div class='main_User'>" .($same[2]) . "</div>";
$bu = "<div class='main_Msg'>" .($same[3]) . "</div>";
$bu = "<div class='main_Date'>" . ($same[4]) . "</div>";
$json  =array('bu'=>$bu);
echo json_encode($json);        

【问题讨论】:

    标签: php json ajax


    【解决方案1】:

    您可以使用 dataType : 'html' 来处理您不需要 json 编码的内容

    //js
      function mpo() 
     {
         $.ajax({
             url: "main.php",
             cache: false,
             dataType : 'html'
             success: function(html){
                 $("#show_div").html(html);
             }
         });
     }
    
    //php
    
    $bu = "<div class='main' style='margin-left:" .($level*60). "px'>";     
    $bu = "<div class='main_one'>";
    $bu = "<div class='main_User'>" .($same[2]) . "</div>";
    $bu = "<div class='main_Msg'>" .($same[3]) . "</div>";
    $bu = "<div class='main_Date'>" . ($same[4]) . "</div>";
    
    echo $json;die;
    

    【讨论】:

    • 我也同意 jeroen。如果您只想使用 json 编码方式,那么 jeroen 方式是完美的
    【解决方案2】:

    你缺少两件事:

    1. 您(可能...)需要解析 json。
    2. 您需要从解析的对象中获取正确的元素。

    要让jQuery自动解析json,你可以设置dataType:

     $.ajax({
         url: "main.php",
         dataType: 'json',
         ^^^^^^^^^^^^^^^^ set the data type of the returned data
         cache: false,
         success: function(html){
             $("#show_div").html(html.bu);
                                 ^^^^^^^ get the correct element
         }
     });
    

    【讨论】:

    • 这种方式怎么办?例如 "success:function(data){ var content = ''; var data = $.parseJSON(data); $.each(data, function(i, post) { content += '
      ' + post.post_title + '
      '; }); $(content).appendTo("#results"); }, "
    猜你喜欢
    • 2018-09-10
    • 2012-11-07
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    • 1970-01-01
    相关资源
    最近更新 更多