Java Reference
In-Depth Information
Hello Ajax!
The HTML file is called hello.htm and contains the following:
hello.htm
<h1>Hello Ajax!</h1>
For the external API we'll use the site JSON Test, which provides a testing service for
JSON data. The URL http://ip.jsontest.com/ will return the IP address of the
computer being used in JSON format.
Note: Enabling CORS
The files stored on SitePoint's AWS servers and the JSON Test website al-
low CORS by setting Access-Control-Allow-Origin to ' * ' in the
HTTP header. Hence, any domain can request data from its website using
Ajax. In a real-world application, the files being requested will normally be
hosted on the same server as the site requesting them, so CORS would be
unnecessary.
Now we need a JavaScript file. This should be called scripts.js and can be saved in the same
directory as the other files. It contains this code:
scripts.js (excerpt)
var text = document.getElementById("text");
var html = document.getElementById("html");
var api = document.getElementById("api");
It assigns a variable to each of the three buttons in the HTML file. Next, we'll add some
code that will assign an event handler to each button:
scripts.js (excerpt)
text.addEventListener("click", function(){
request("https://s3.amazo
naws.com/sitepoint-book-content/jsninja/hello.txt") },
false);
html.addEventListener("click", function(){
Search WWH ::




Custom Search