如何使用AJAX调用来刷新img src

时间:2017-04-19 21:34:10

标签: javascript php ajax image xmlhttprequest

我有一个PHP脚本 picQuery.php ,它返回图片的路径。我有另一个调用picQuery.php的脚本然后应该显示图片,但我无法弄清楚如何去做。

我的代码在picFrame中显示文件路径。我想要的是类似下面的一行,我已经注释掉它,因为它不起作用。怎么写呢?

HTML:

<!DOCTYPE html>
<html>
<body>
<form action=""> 
<button type="button" onclick="getPic(this.value)">Click Me!</button>
</form>
<p id="picFrame"</p>

<!--<img src=<p id="picFrame"</p>  alt="text"  style="width:304px;height:228px;">-->

<script>
function getPic() {
  var xhttp;
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("picFrame").innerHTML = this.responseText;
      alert('response = '.this.responseText);
    }
  };
  xhttp.open("GET", "picQuery.php?q=4", true);
  xhttp.send();   
}
</script>
</body>
</html>

picQuery.php

<!DOCTYPE html> <html> <body> <?php echo "PIC1.jpg" ?> </body> </html>

1 个答案:

答案 0 :(得分:1)

有多种方法可以实现。

最简单的可能是创建Image的实例,将responseText分配给图像的src属性,相应地设置style属性,然后设置innerHTML id picFrame 的元素到图片的outerHTML

xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var image = new Image();
        image.src= this.responseText;
        image.style = "width:304px;height:228px;";
        document.getElementById("picFrame").innerHTML = image.outerHTML;
    }
}

this phpfiddle中看到它。

否则,如果 id 属性已更改,或者作为段落元素的子项通过DOM访问,则可以使用当前已注释掉的<img>标记。但是,如果 src 属性的初始值为空或图像的URL无效,则浏览器可能会显示损坏的图像图标。

因此图像可以像这样更新:

<p id="picFrame">
    <img alt="text" id="picFrameImg" style="width:304px;height:228px;" />
</p>

然后通过Javascript访问:

xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
    document.getElementById('picFrameImg').src = this.responseText;
}

请参阅下面的演示。希望AJAX在长期内仍然可行,但考虑到phpfiddle代码文件,它可能不会。如果它停止工作,this plunker可能是一个很好的演示,但请记住 picQuery.php NOT 作为常规PHP文件执行。

&#13;
&#13;
function getPic() {
  var xhttp;
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("picFrameImg").src = this.responseText;
    }
  };
  xhttp.open("GET", "http://main.xfiddle.com/code_65644594.php?q=4", true);
  xhttp.send();   
}
&#13;
<form action="">
  <button type="button" onclick="getPic(this.value)">Click Me!</button>
</form>
<p id="picFrame">
  <img alt="text" id="picFrameImg" style="width:304px;height:228px;" src="" />
</p>
&#13;
&#13;
&#13;

更新4/21/2017

提供的PHP代码不适用于AJAX方法。它应该返回图像的路径,而不是围绕它的html标签。

从而更新PHP:

<!DOCTYPE html> <html> <body> <?php echo "PIC1.jpg" ?> </body> </html>

对此:

<?php echo "PIC1.jpg"; ?>

这样,AJAX代码基本上就是从

更新图像标签
<img alt="text" id="picFrameImg" style="width:304px;height:228px;" />

到此:

<img alt="text" id="picFrameImg" style="width:304px;height:228px;" src="PIC1.jpg" />