代码之家  ›  专栏  ›  技术社区  ›  Mona Coder

Ajax使用HTML数据类型将布尔值和HTML从服务器传递到客户端

  •  2
  • Mona Coder  · 技术社区  · 7 年前

    我有一个PHP文件,它用 dataType: 'HTML', . PHP看起来像

    if( $result->num_rows > 0 ){
        ....
        echo '<p>There are some user already </p>';
    } 
    else{
        echo '<p>List is empty </p>';
    }
    

    ajaxcall.done(function(data) {  
      $('#call-result').html(data);
    });
    

    1 回复  |  直到 7 年前
        1
  •  1
  •   miken32 Amit D    7 年前

    只需使用JSON进行响应:

    <?php
    if ($result->num_rows > 0) {
        $html = '<p>There are some user already </p>';
        $result = false;
    } else{
        $html = '<p>List is empty </p>';
        $result = true;
    }
    $response = ["html"=>$html, "result"=>$result];
    header("Content-Type: application/json");
    echo json_encode($response);
    

    然后,在JS中:

    ajaxcall.done(function(data) {
        var result = data.result;
        $('#call-result').html(data.html);
    });
    

    jQuery将自动解析类型为的响应 json