jquery ajax,如何在处理页面中调用onload事件?
我尝试通过jquery ajax将值从页面a发布到页面b。 但是当我需要在句柄页面中有一个onload事件时。我尝试了2种方法,但都失败了。如何正确调用还是有bug?
a.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>
b.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>
I have try to post value from page a to page b via jquery ajax.
But when I need a onload event in the handle page. I tried 2 ways, but all failed. How to call correctly or it is a bug?
a.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>
b.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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您将 HTML 插入文档时,所有脚本都会在文档的上下文中执行。这意味着
window.onload
引用当前窗口
的load
事件。由于插入被延迟(通过等待click
事件),因此window.onload
事件已经被触发。您可以将一个函数附加到load
事件,但它永远不会被触发。最好将函数调用直接放入
script
元素中:这意味着 jQuery 将在脚本添加到文档时执行该脚本。
When you insert HTML into your document, any scripts are executed with the document's context. That means that
window.onload
refers to theload
event of the currentwindow
. Given that the insertion is delayed (by waiting for theclick
event), thewindow.onload
event has already been triggered. You can attach a function to theload
event, but it will never be triggered.It's probably best to put the function call straight into your
script
element:This means that jQuery will execute the script as it's added to the document.
您需要更改
为:
您需要更改
为:
您需要更改
为:
You need to change:
to:
You need to change:
to:
You need to change:
to: