<body>
<div>
<img id="random-dog" src=""/>
</div>
<button>Get me a doggo</button>
<script>
$("button").click(function () {
$("#random-dog").load("https://dog.ceo/api/breeds/image/random", function (responseTxt, statusTxt, xhr) {
if (statusTxt == "success")
this.setAttribute("src", JSON.parse(responseTxt).message);
console.log("External content loaded successfully!");
if (statusTxt == "error")
console.log("Error: " + xhr.status + ": " + xhr.statusText);
});
});
</script>
</body>
在回调函数内部,如果状态文本为成功,则处理响应并将其设置为this
src 属性。this
表示选择器元素。
API结构是:
{
"message": "https://images.dog.ceo/breeds/whippet/n02091134_10242.jpg",
"status": "success"
}