I wish a page to fully load before issuing an ajax call to update database. I can ca开发者_开发问答ll a javascript function in the body onload event so the page is fully loaded, but I'm not sure how to trigger the Ajax call from there.Is there any better way of achieiving this (Upadating database after page load)?
This is really easy using a JavaScript library, e.g. using jQuery you could write:
$(document).ready(function(){
$.ajax({ url: "database/update.html",
context: document.body,
success: function(){
alert("done");
}
});
});
Without jQuery, the simplest version might be as follows, but it does not account for browser differences or error handling:
<html>
<body onload="updateDB();">
</body>
<script language="javascript">
function updateDB() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "database/update.html", true);
xhr.send(null);
/* ignore result */
}
</script>
</html>
See also:
- Launching Code on Document Ready
- jQuery ajax
- http://msdn.microsoft.com/en-us/library/ms535874(VS.85).aspx
You can use jQuery to do that for you.
$(document).ready(function() {
// put Ajax here.
});
Check it here:
http://docs.jquery.com/Tutorials:Introducing_%24%28document%29.ready%28%29
It's even easier to do without a library
window.onload = function() {
// code
};
Or with Prototype:
Event.observe(this, 'load', function() { new Ajax.Request(... ) );
Or better, define the function elsewhere rather than inline, then:
Event.observe(this, 'load', functionName );
You don't have to use jQuery or Prototype specifically, but I hope you're using some kind of library. Either library is going to handle the event handling in a more consistent manner than onload, and of course is going to make it much easier to process the Ajax call. If you must use the body onload attribute, then you should just be able to call the same function as referenced in these examples (onload="javascript:functionName();"
).
However, if your database update doesn't depend on the rendering on the page, why wait until it's fully loaded? You could just include a call to the Ajax-calling function at the end of the JavaScript on the page, which should give nearly the same effect.
精彩评论