在我看来,动态加载外部图片的最简单方法是从包含图片 URL(如)的 PHP 脚本中获取JSON对象。http://www.example.com/pictures/getPicture/YOUR_PICTURE_ID
服务器端
<?php
$pictureUrl = 'http://example.com/pictures/picture.jpg'; //You can get it with a database query
$pictureName = 'Foo';
$pictureAltText = 'Bar';
// You can do some stuff here.
// At the end of the script, write result.
echo json_encode(compact('pictureUrl', 'pictureName', 'pictureAltText'));
?>
客户端
<script type="text/javascript">
// With jQuery
$.getJSON('http://www.example.com/pictures/getPicture/YOUR_PICTURE_ID', function(data){
console.log(data.pictureUrl, data.pictureName, pictureAltText);
var img = new Image();
img.src = data.pictureUrl;
img.setAttribute('alt', data.pictureAltText);
img.onload = function(){
// Displaying picture when download completed
$(img).appendTo('body');
}
});
</script>
如果您不使用 jQuery,则必须使用XMLHttpRequest来获取 JSON 编码的响应并对其进行解析(您可以在https://developer.mozilla.org/en-US/docs/JSON上查看 MDN 文档)。