在页面的onload Javascript的Ajax调用页面、onload、Ajax、Javascript

2023-09-10 16:54:21 作者:几钵

我想一个页面发出Ajax调用,更新数据库之前完全加载。我可以调用体内onload事件的JavaScript函数,以便在网页完全加载,但我不知道如何触发there.Is Ajax调用有achieiving这个(页面加载后Upadating数据库)中没有更好的办法?

I wish a page to fully load before issuing an ajax call to update database. I can call 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)?

推荐答案

这是很容易使用的JavaScript库,如:使用jQuery你可以写:

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");
        }});
});

没有jQuery的,最简单的版本可能如下,但它没有考虑浏览器的差异或错误处理:

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>

另请参阅:

http://docs.jquery.com/How_jQuery_Works#Launching_$c$c_on_Document_Ready http://api.jquery.com/jQuery.ajax/ http://msdn.microsoft.com/en-us/library/ms535874(VS.85).aspx http://docs.jquery.com/How_jQuery_Works#Launching_Code_on_Document_Ready http://api.jquery.com/jQuery.ajax/ http://msdn.microsoft.com/en-us/library/ms535874(VS.85).aspx