There is page X on server x with a html file like this
<script type="text/javascript" src="http://pageYserverY.com/remote.php?hat=strong"></script>
<div name="lev">Hallo world</div>
Consider the JS file is included from a remote server Y.
The file on page Y (remote.php) looks like this:
<?php
Header("content-type: application/x-javascript");
$hat = $_GET["hat"];
echo "document.write(\"$hat\");"; // write it once
?>
document.getElementsByName("lev").innerHTML="Hello World AGAIN";
Why is it not changing the div. Is my whole approach and my understanding of cross-browser JS wrong?
btw: the calling a php generated js is a approach google itself uses on recaptcha and google ads.
I think you will find it is simply an ordering problem. The JavaScript is executing before the div is ready.
Move the script beneath the div, like so:
<div name="lev">Hallo world</div>
<script type="text/javascript"
src="http://pageYserverY.com/remote.php?hat=strong"></script>
Is better that you use getElementById
that getElementsByName
.
The GetElementsByName
method returns an array, and when you tried to call element.focus()
you got an error because there is no focus
method on an array. When you get an error in the event handler it won't prevent the form from posting.
If you use GetElementById
you should use element
to access the element, and if you use GetElementsByName
you should use element[0]
.
Repeat
getElementById gets an element via an id. getElementsByName returns an Array of elements by their name.
Then this is work:
<div id="lev">Hallo world</div>
<?php
Header("content-type: application/x-javascript");
$hat = $_GET["hat"];
echo "document.write(\"$hat\");"; // write it once
?>
document.getElementById("lev").innerHTML="Hello World AGAIN";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.