简体   繁体   English

Javascript ajax调用页面onload

[英]Javascript ajax call on page onload

I wish a page to fully load before issuing an ajax call to update database. 我希望在发出更新数据库的ajax调用之前完全加载页面。 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)? 我可以在body onload事件中调用一个javascript函数,这样页面就完全加载了,但是我不知道如何从那里触发Ajax调用。有没有更好的方法来实现这个(页面加载后的Upadating数据库)?

This is really easy using a JavaScript library, eg using jQuery you could write: 使用JavaScript库非常简单,例如使用你可以编写的jQuery:

$(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: 没有jQuery,最简单的版本可能如下,但它不考虑浏览器差异或错误处理:

<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: 也可以看看:

You can use jQuery to do that for you. 您可以使用jQuery为您执行此操作。

 $(document).ready(function() {
   // put Ajax here.
 });

Check it here: 在这里查看:

http://docs.jquery.com/Tutorials:Introducing_%24%28document%29.ready%28%29 http://docs.jquery.com/Tutorials:Introducing_%24%28document%29.ready%28%29

Or with Prototype: 或者使用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. 您不必专门使用jQuery或Prototype,但我希望您使用某种类型的库。 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. 这两个库都将以比onload更一致的方式处理事件处理,当然这将使处理Ajax调用变得更加容易。 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();" ). 如果必须使用body onload属性,那么您应该只能调用这些示例中引用的相同函数( 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. 您可以在页面上的JavaScript末尾包含对Ajax调用函数的调用,这应该会产生几乎相同的效果。

It's even easier to do without a library 没有图书馆就更容易了

window.onload = function() {
    // code
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM