How to make script pulled in with HttpRequest working

Hi,
I’ve mockup this simple method which would use in real product. But unfortunately, i can’t make the script working.


<!DOCTYPE html>
<html>
	<head>
		<title>Pass Script</title>
	</head>
	<body>
		<button id=button>Get</button>
		<div id='log'></div>
		<script>
			var log = function(msg) {document.getElementById('log').innerHTML = msg + "<br/>";};
			var button = document.getElementById('button');
			button.addEventListener('click', function(e) {
				var xhr = new XMLHttpRequest();
				xhr.open('GET', 'test.php', true);
				xhr.send();
				xhr.onreadystatechange = function () {
					if (xhr.readyState === 4) {
						if (xhr.responseText === 'undefined') {
							return;
						} else {
							log(xhr.responseText);
						}
					}
				};
			});
		</script>
	</body>
</html>

And the test.php:


<input type=text name=data />
<script>
	console.log('You\\'ve got data');
</script>

How do I make the script on the test.php file working?

Thank you,

Hi,

As far as I know, the browser won’t execute JS code that is dynamically added inline to the page. If you insert a script tag that links to an external JS file then the code will be loaded and run. Depending on what you’re trying to do though, there might be better ways to achieve it.

Hi,
I’ve tried what you suggested. It’s not working.

Test.php


<input id=data_input type=text name=data />
<script src='test.js'></script>

test.js


var data_input = document.getElementById('data_input');
console.log(data_input);

Never mind I get it done. Thanks

Hmm, OK it seems for some reason the browser will only load the JS if you create a script element and append it to the DOM:

var script = document.createElement( 'script' );
script.src = url;
document.body.appendChild( script );

So you could do something like this in your log function:

var log = function(msg) {
	var logEl = document.getElementById('log'),
	    s1,
	    s2;

	logEl.innerHTML = msg + "<br/>";

	// Grab script element and remove from DOM
	s1 = logEl.getElementsByTagName('script')[0];
	logEl.removeChild(s1);

	// Create new script element with same source as s1
	s2 = document.createElement('script');
	s2.src = s.src;
	
	// Append new script to DOM
	document.body.appendChild(s2);
};

But, is it not possible to include the necessary JS in the parent page, and just trigger it when the remote page has been loaded and inserted into the DOM? That would seem more straightforward.

Thank you,
You’re right. It has to attache the script to the DOM and after the html that being pulled from the test page.