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>
When you insert HTML into your document, any scripts are executed with the document’s context. That means that
window.onloadrefers to theloadevent of the currentwindow. Given that the insertion is delayed (by waiting for theclickevent), thewindow.onloadevent has already been triggered. You can attach a function to theloadevent, but it will never be triggered.It’s probably best to put the function call straight into your
scriptelement:This means that jQuery will execute the script as it’s added to the document.