GET data from server via JQuery call and load into DIV without refreshing page
I've spent the best part of 90 minutes sifting through the many tutorials relating to this problem.
Instead of using the rather long winded way of creating a XHR object , sending the request, getting the data back, doing a getElementById to find the div then loading the response into the div. I'm looking for a far more simpler - easier on the eye way of doing it and so have found myself looking at JQuery.
However none of the tuts seem to开发者_开发技巧 do what i want unless i'm overlooking something. I just want to pass in a url, perform the request - data is passed back as html, then i want to inject it into a specific div.
Can someone please show me a simple solution to this problem, or link me to a straightforward tutorial if one is known?
Thanks in advance.
$('#divID').load('yourURL');
edit just noticed that you want to "inject" it. The previous line will replace the contents of the div. If you want to append it, you'd do the following:
$.get('yourURL', function(data) {
$('#divID').append(data);
});
check out:
http://www.javascriptkit.com/script/script2/ajaxpagefetcher.shtml
he has posted cut and paste for ajax loading on both page load as well as when a link is clicked.
For my purposes, instead of having the URL in the HREF, I involked the ajax load from the onClick option of the anchor tag, but had to remove javascript: from javascript:ajaxpagefetcher.load to get it to work in that configuration; this was due to the fact that the href URL of the anchor tag I wanted to be a totally different link than the ajax page. Ie, my hyper link was for a banner ad to the URL of said third party web site that when user clicked opens up in a new window, (target ="_blank"), breaking out of frames my site is running in so as to open the new third party web site with the proper URL including affiliate code information instead of being a frame on my site, but on a user clicking on said banner ad link, i wanted to involke a counter script to accumulate the total number of clicks for that particular banner ad.
This is all working for me to load a htm file into a DIV container which is hidden from the user, as far as the ajax load fetching of the counter script is concerned.
This should do what you need, it loads the response of the url into the div.
<div id="example"></div>
<script type="text/javascript">
$("#example").load("http://mysite/ajaxpage");
</script>
jQuery "load" documentation:
http://api.jquery.com/load/
You can also add a callback function...
<div id="example"></div>
<script type="text/javascript">
$("#example").load("http://mysite/ajaxpage", function () { alert("Done"); });
</script>
Take a look at http://api.jquery.com/load/ should be as simple as:
$('#result').load('ajax/test.html');
精彩评论