如何使用 XMLHttpRequest 获取 .jpg 图像?
How to GET a .jpg image using XMLHttpRequest?
例如,我可以使用此方法轻松获取 .txt 文件,但是当我尝试获取图像时,它会发送一堆未编码的字母,例如“@R�J”,我如何才能获取图像呢是吗?
<!DOCTYPE html>
<html>
<body>
<h1 id="demo">Let AJAX change this text</h1>
<button id="button">Change Content</button>
<script>
document.getElementById('button').addEventListener('click', function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "images.jpg", true);
xhttp.send();
});
</script>
</body>
</html>
编辑:
我真的想出我可以做到这一点document.getElementById("demo").setAttribute('src', 'https://placeimg.com/640/480/any');
并在 HTML <img id="demo" src="" />
它适用于外部资源,但我的服务器中的图像呢?
如果图像在您的服务器上,您可以通过绝对地址 src="http://localhost:portnumber/pathOfTheImage/image.png"
或相对于您的站点文件夹 src="/images/image.png"
.
获取它
例如,我可以使用此方法轻松获取 .txt 文件,但是当我尝试获取图像时,它会发送一堆未编码的字母,例如“@R�J”,我如何才能获取图像呢是吗?
<!DOCTYPE html>
<html>
<body>
<h1 id="demo">Let AJAX change this text</h1>
<button id="button">Change Content</button>
<script>
document.getElementById('button').addEventListener('click', function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "images.jpg", true);
xhttp.send();
});
</script>
</body>
</html>
编辑:
我真的想出我可以做到这一点document.getElementById("demo").setAttribute('src', 'https://placeimg.com/640/480/any');
并在 HTML <img id="demo" src="" />
它适用于外部资源,但我的服务器中的图像呢?
如果图像在您的服务器上,您可以通过绝对地址 src="http://localhost:portnumber/pathOfTheImage/image.png"
或相对于您的站点文件夹 src="/images/image.png"
.