开发者

make AJAX\jQuery\JavaScript load pictures?

I want to load picture from web server without refreshing the page. I have simple page:

<body><h1>Test</h1>
      <div id="mydiv">
         <img src="animals.jpg"/>
      </div>
</body>
</html>

the point is that animals.jpg content changes (i.e now animals.jpg can be picture of wolf but after minute it will be changed to a cat) however the开发者_开发技巧 name(animal.jpg) stays ( server overwrites the image content only ) so what i want is when i click on the picture it will re-load it from the server.

what i did so far (actually it's made of pieces of examples i found :) ):

    $(document).ready(function(){
        $('#mydiv').click(function(){
        //$('#mydiv').load("animals.jpg") // loads text instead of image
        //$("#mydiv").append("<img src='animals.jpg'/>"); // appends old picture
        //$("#mydiv").html("<img src='animals.jpg'/>") // not responds at all
    }); 
})

not working, see the comments.

Though I can load html's:

loadme.html:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"/></script>
<script type="text/javascript">
   $(document).ready(function(){
     $('#mydiv').click(function(){
     $('#mydiv').load("h1.html")
   }); 
 })


</script>

</head>

<body><h1>Test</h1>
<div id="mydiv">
load me!
</div>
</body>
</html>

h1.html:

Text

now when i change h1.html 'text' on something else and i click on 'load me!' in load.html it will updated content always. That's what i want to achieve with images :/


You need to change the image's src attribute to get it to reload. As the src is supposed to stay the same, append a random string to the end of it. This'll make the browser think it's a new image.

$('#mydif>img').attr('src', 'animals.jpg?random=' + Math.random());


Easiest way, for me:

<img id="myimg" src="animal.jpg"/>

Just set the src attribute with Javascript:

function f()
{
   var img = document.getElementById("myimg");
   img.src = "your_new_pic.jpg";
}

Of course, if you need animations or other cool stuff, it's better to use JQUERY.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜