簡體   English   中英

如何使用AJAX調用刷新img src

[英]How to use AJAX call to refresh img src

我有一個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>

有多種方法可以實現。

最簡單的可能是創建一個實例圖片 ,分配的responseText到SRC圖像的屬性,設置樣式相應的屬性,然后設定id picFrame到元素的innerHTML 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;
    }
}

看到它在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;
}

請參閱下面的演示。 鑒於phpfiddle代碼文件,希望AJAX仍然可以長期運行,盡管可能無法長期運行。 如果它停止工作, 可能會是一個很好的演示,但請記住, picQuery.php 不會作為常規PHP文件執行。

 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(); } 
 <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> 

更新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" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM