I'm newbie in javascript and My project can't use AJAX or any Framework . . .
It's simple code but still curious what's wrong with it
<html>
<head>
<script type="text/javascript" src="onejs.js"></script>
<link href="onecss.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="myDiv" class="subMenu" onclick="test(this)">CLICK</div>
</body>
</html>
onejs.js
function test(id) {
var s = document.createElement('script');
s.id = 'dynScript';
s.type='text/javascript';
s.src = "http://echo.jsontest.com/one/111oneoneone/key/value";
var obj = JSON.parse(s);
id.innerHTML = (obj.key);
}
When I click in "CLICK" it doesn't change.
asked Dec 11, 2013 at 10:20
crazyoxygen
7161 gold badge12 silver badges31 bronze badges
1 Answer 1
You are trying to load JSON as if it was a JavaScript script. It isn't, so you can't.
Normally you would use the XMLHttpRequest object for this type of job.
However, since you are ruled out Ajax (the process of using JavaScript to make HTTP requests), this isn't an option, so you would have to embed the data into the HTML when it initially loads.
answered Dec 11, 2013 at 10:22
Quentin
949k137 gold badges1.3k silver badges1.4k bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Denys Séguret
But then, this would be "AJAX".
crazyoxygen
OK My api can send data via XML too. So I should go on XML ,right ?
Quentin
XML isn't JavaScript either, so changing data format to that wouldn't help.
Quentin
You can use XMLHttpRequest to fetch any kind of data. It only has XML in the name because the developers needed to persuade management to put it into the next release of the product and XML was a cool buzzword at the time.
lang-js
JSON.parse, or the remote host providing the JSON allows you to specify a consumer callback (google JSONP).