如何通过ajax显示从PHP接收的图像?

时间:2017-08-23 13:21:48

标签: jquery html ajax

我必须通过ajax显示从PHP接收的图像。我可以显示名称<span id="pic_name">Pic name here</span>,但如何显示图像<img src="images/pic/picname" />

   //alert(a);
         $.ajax({
                  type: "POST",
                   url: "includes/compare.php", // 
                   data:'id='+a,
                 success: function(msg){
                 msg = msg.split(',');
                 $("#pics_name").html("<img src='images/profile/"+msg+"' alt='' />");
                 $("#pics_user").html(msg);
                 $("#username").html(msg);
                 $("#email").html(msg);
                      },
                    error: function(){
                    alert("failure");
                    }
                  });

PHP

 $compare_u=$_POST['id'];
                $sql_compare="SELECT * FROM request WHERE Id=$compare_u";
                $compare_query=$conn->query($sql_compare);
                if ($compare_query->num_rows > 0) {
                while($userdata12=$compare_query->fetch_assoc()){ 
                    $compare_pic=$userdata12['profile_pic'];
                    $compare_name=$userdata12['Name'];
                   $compare_user=$userdata12['username'];
                   $compare_user=$userdata12['email'];
                }
            }
         exit();

我们如何显示多个值?

2 个答案:

答案 0 :(得分:0)

检查以下更新的代码..

&#13;
&#13;
$.ajax({
  type: "POST",
  url: "includes/compare.php", // 
  data:'id='+a,
  success: function(msg){
    myObj = JSON.parse(msg);
    for (x in myObj) {
      $("#pics_name").html("<img src='images/profile/"+myObj[x].profile_pic+"' alt='' />"); 
      $("#pics_user").html(myObj[x].Name); 
      $("#username").html(myObj[x].username);
      $("#email").html(myObj[x].email);
    }
  },
  error: function(){
    alert("failure");
  }
});
&#13;
<?php 
  $compare_u=$_POST['id'];
	$sql_compare="SELECT * FROM request WHERE Id=$compare_u";
	$compare_query=$conn->query($sql_compare);
	if ($compare_query->num_rows > 0) {
		$outp = array();
		$outp = $compare_query->fetch_all(MYSQLI_ASSOC);
		echo json_encode($outp);
	}
	exit();
?>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

$.ajax({
  type: "POST",
  url: "includes/compare.php", // 
  data:'id='+a,
  success: function(msg){
  //here  As Image Tag that you create
  // ==> $("#pics_name").html("<img src='"+m-sg+"' alt='' />"); 

 //here  we set directly SRC in Image
  $("#my_image_tag").attr("src",msg);


  },
  error: function(){
    alert("failure");
  }
});