Reputation: 2609
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>
Upvotes: 1
Views: 21095
Reputation: 20415
You need to change:
<script language="JavaScript">
to:
<script type="text/javascript">
You need to change:
function callhello() {
alert('<?php echo $_POST['word']; ?>');
//many other code, for a test, I moved them. and replace a alert call.
}
to:
function callhello() {
alert('<?php echo $_POST["word"]; ?>');
//many other code, for a test, I moved them. and replace a alert call.
}
You need to change:
<body onload="JavaScript:callhello()">
to:
<body onload="javascript://callhello();">
Upvotes: 1
Reputation: 237995
When you insert HTML into your document, any scripts are executed with the document's context. That means that window.onload
refers to the load
event of the current window
. Given that the insertion is delayed (by waiting for the click
event), the window.onload
event has already been triggered. You can attach a function to the load
event, but it will never be triggered.
It's probably best to put the function call straight into your script
element:
<script type="text/javascript"> // the language attribute is deprecated
callhello();
</script>
This means that jQuery will execute the script as it's added to the document.
Upvotes: 4