jquery ajax,如何在句柄页中调用 onload 事件

jquery ajax, how to call onload event in handle page?

本文关键字:调用 onload 事件 句柄 ajax jquery      更新时间:2023-09-26

我尝试通过jquery ajax将值从页面a发布到页面b。但是当我需要在句柄页面中加载事件时。 我尝试了两种方法,但都失败了。如何正确调用或这是一个错误?

答.php

<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript">     
jQuery(document).ready(function(){
    $("a").click(function(){
     $.ajax({
         url: "b.php", 
         dataType: "html",
         type: 'POST', 
         data: "word="+"hello", 
         success: function(data){ 
            $("#show").html(data);
         }
      });
    });
});
</script>
<a href="#">click</a>
<div id="show"></div>

乙.php

<script language="JavaScript">
   function callhello() {
       alert('<?php echo $_POST['word']; ?>');
       //many other code, for a test, I moved them. and replace a alert call.
   }
</script>
<body onload="JavaScript:callhello()"><!-- way 1, put onload here, not run -->
    Blah~~ Blah~~ Blah~~
<script language="JavaScript">// change to text/javascript or even remove, no effect
window.onload = function() {
  callhello();
};
</script><!-- way 2, put onload here, still not run. -->
</body>

将 HTML 插入文档时,任何脚本都将与文档的上下文一起执行。 这意味着window.onload是指当前windowload事件。 假设插入延迟(通过等待click事件),则已触发window.onload事件。 可以将函数附加到 load 事件,但它永远不会被触发。

最好将函数调用直接放入 script 元素中:

<script type="text/javascript"> // the language attribute is deprecated
  callhello();
</script>

这意味着 jQuery 将在脚本添加到文档中时执行脚本。

您需要更改:

<script language="JavaScript">

自:

<script type="text/javascript">

您需要更改:

function callhello() {
    alert('<?php echo $_POST['word']; ?>');
    //many other code, for a test, I moved them. and replace a alert call.
}

自:

function callhello() {
    alert('<?php echo $_POST["word"]; ?>');
    //many other code, for a test, I moved them. and replace a alert call.
}

您需要更改:

<body onload="JavaScript:callhello()">

自:

<body onload="javascript://callhello();">