You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In the above code, we create a new XMLHttpRequest instance on line 2. Then, we add an event listener for the readystatechange event. This fires whenever the XMLHttpRequest readyState changes.
65
+
In the above code we essentially grab a handle to the button in our HTML (line 16) and add a *click* event listener (line 17). In our event listener, we define our callback function as loadDataFromServer.
66
+
67
+
We define our loadDataFromServer callback beginning on line 2.
87
68
88
-
In the event handler we check to see if the readyState = READYSTATE_COMPLETE (value of 4). Then, we check to see if the status is either 200 or 304, both values are success indicators.
69
+
We create a XMLHttpRequest request object (line 3) and add a *readystatechange* event handler. This fires whenever the request's readyState changes.
70
+
71
+
In the event handler we check to see if the readyState = 4, indicating the request has completed. Then, we check the request status value. Both 200 or 304 represent a succsessful request. Anything else represents an error condition.
89
72
90
73
If the request was indeed successful, we eval the JSON returned from the server and assign it to a data variable. At this point, we can use the returned data in any way we need to.
91
74
92
75
The last thing we need to do is actually make our request.
93
76
94
-
Line 12 opens a 'GET' request to retreive the data.json file.
77
+
Line 13 opens a 'GET' request to retreive the data.json file.
78
+
79
+
Line 14 sends our request to the server.
80
+
81
+
## Older Browser Support
82
+
83
+
If your application needs to target older versions of Internet Explorer, you will need to ensure the XMLHttpRequest object exists. You can do this by including this code before creating the XMLHttpRequest instance.
84
+
85
+
{% highlight coffeescript %}
86
+
if (typeof @XMLHttpRequest == "undefined")
87
+
console.log 'XMLHttpRequest is undefined'
88
+
@XMLHttpRequest = ->
89
+
try
90
+
return new ActiveXObject("Msxml2.XMLHTTP.6.0")
91
+
catch error
92
+
try
93
+
return new ActiveXObject("Msxml2.XMLHTTP.3.0")
94
+
catch error
95
+
try
96
+
return new ActiveXObject("Microsoft.XMLHTTP")
97
+
catch error
98
+
throw new Error("This browser does not support XMLHttpRequest.")
99
+
{% endhighlight %}
100
+
101
+
This code ensures the XMLHttpRequest object is available in the global namespace.
0 commit comments