我有一个链接,当前指向我项目中的.txt文件。我需要将该链接指向.jpg。目前,当我使用.jpg时,我会得到宏。
我只需要从项目中的图像dir异步拉取文件的链接。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>JavaScript Ajax Demo</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<!--<link href="styles/bootstrap.min.css" rel="stylesheet">-->
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div id="index">
<a href="words/a.txt">A</a>
<a href="words/b.txt">B</a>
<a href="words/c.txt">C</a>
</div>
<form>
<input type="submit" />
</form>
<div id="output">
</div>
</div>
<script>
window.addEventListener("load", function () {
var indx = g("index");
indx.addEventListener("click", function (e) {
getData(e.target.href);
e.preventDefault();
});
});
var temp = document.createElement("img");
temp.src = "linktoyourimage.jpg"
function getData(url) {
// 1 - new XMLHttpRequest
var xhr = new XMLHttpRequest(); // readyState = 0
// 2 - Open
//url = "http://google.com";
xhr.open("GET", url); // readyState = 1
// 3 - Set onreadystatechange event handler
xhr.onreadystatechange = gotData;
// 4 - Send
xhr.send(); //readyState = 2
}
function gotData() {
// readyState = 3 -> Receiving Data
// readyState = 4 -> Ready to process response data
if (this.readyState == 4 && this.status == 200) {
var op = g("output");
op.innerHTML = this.responseText;
}
}
function g(id) {
return document.getElementById(id);
}
</script>
<!-- /.container -->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<!--<script src="scripts/bootstrap.min.js"></script>-->
</body>
</html>
答案 0 :(得分:0)
你的问题不是很清楚,但我会尽力提供帮助并猜出你真正想要的......
如果是图片,您不需要去获取其内容,但您可以更改src
元素的img
。
尝试使用它:
function getData(url) {
if(url.substr(-3) === "jpg" ) {
//if this is a jpg file, just point your img container to that
temp.src = url;
}
else{
//otherwise go out and get the txt file, later display it in some container
// 1 - new XMLHttpRequest
var xhr = new XMLHttpRequest(); // readyState = 0
// 2 - Open
//url = "http://google.com";
xhr.open("GET", url); // readyState = 1
// 3 - Set onreadystatechange event handler
xhr.onreadystatechange = gotData;
// 4 - Send
xhr.send(); //readyState = 2
}
}
另外,将某些链接更改为指向jpg
图片。
我还没有测试过这段代码,只是写信告诉你这个概念。如果它失败了,请耐心等待。