weixin_33713503 2017-10-04 15:03 采纳率: 0%
浏览 28

PHP:在$ .ajax中返回html

I am trying to return HTML through $.ajax, this is my code:

 $(document).ready(function() {

    $(".click").on('click',function() {                
      var id= $(this).attr("data-id"); 

      $.ajax({     
        type: "POST",
        url: "getevents.php", 
        data: {id:id}, 
        dataType: "html",                  
        success: function(response){                    
            alert(response);
            $('.headimg').html(response);
        }
     });
 })}) 

My PHP code:

 $singleevent = mysqli_query($link, "SELECT `content` FROM `events` WHERE `id` 
= $id") ;
if(!$singleevent){
    echo mysqli_error();
}
else {

$result = mysqli_fetch_array($singleevent); 
 echo $result; 
}

Link to be clicked:

<a class='click' data-id='<?=$rows["id"];?>'><?=$rows['title'];?></a>

In alert() this is what I get Array

If I do print_r() instead of echo this is what I get

 [0] => <div class='row'>
  <div class='col-sm-12'>
   <img src='img/img.png' class='img-responsive'>
  </div>
  <div class='col-xs-12'>
   <p> October 14th  | All Day</p>

  </div>

</div>
    [content] => <div class='row'>
  <div class='col-sm-12'>
   <img src='img/img.png' class='img-responsive'>
  </div>
  <div class='col-xs-12'>
   <p> October 14th  | All Day</p>

  </div>

</div>

How to I put it in HTML rather than array?

  • 写回答

1条回答 默认 最新

  • weixin_33722405 2017-10-04 15:08
    关注

    The result is what you get if you do echo array(1,2,3), you can not echo a array. Besides that, a PHP array isn't a Javascript array, so javascript doesnt understand the result.

    You currently fetch the result from the database, which has two values because you fetch it as fetch_array(), which returns the data double:
    - Once as numerical values ([0],[1],[2] etc)
    - Once as named values (['content'],['example'],['etc'])

    To remedy this, use fetch_assoc(). That will only return the last one (the named).

    But, then you still have an array with a value, so javascript will still get "Array" as you try to echo that. You can now do echo $result['content']; to fix this.


    There is a (IMO) better method, which is a bit more complex, but a lot more expendable (what if you want 2 or 3 or ... values returned?), which is called JSON format.

    In PHP you do echo json_encode($result); which will result in a weird look array in text format. Now you go to you Javascript AJAX function and add dataType: "json" to it. You can now use response.content, or response.example, or response.whateverYouSelectInPHP

    评论

报告相同问题?

悬赏问题

  • ¥30 电脑误删了手机的照片怎么恢复?
  • ¥15 (标签-python|关键词-char)
  • ¥15 python+selenium,在新增时弹出了一个输入框
  • ¥15 苹果验机结果的api接口哪里有??单次调用1毛钱及以下。
  • ¥20 学生成绩管理系统设计
  • ¥15 来一个cc穿盾脚本开发者
  • ¥15 CST2023安装报错
  • ¥15 使用diffusionbert生成文字 结果是PAD和UNK怎么办
  • ¥15 有人懂怎么做大模型的客服系统吗?卡住了卡住了
  • ¥20 firefly-rk3399上启动卡住了