在页面的onload Javascript的Ajax调用 [英] Javascript ajax call on page onload

查看:350
本文介绍了在页面的onload Javascript的Ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个页面发出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>

另请参阅:

  • <一个href="http://docs.jquery.com/How_jQuery_Works#Launching_$c$c_on_Document_Ready">http://docs.jquery.com/How_jQuery_Works#Launching_$c$c_on_Document_Ready
  • http://api.jquery.com/jQuery.ajax/
  • <一个href="http://msdn.microsoft.com/en-us/library/ms535874(VS.85).aspx">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

这篇关于在页面的onload Javascript的Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆