@@ -147,3 +147,53 @@ object KeyCode {
147
147
val y = 89
148
148
val z = 90
149
149
}
150
+
151
+ import scala .concurrent .{Promise , Future }
152
+ /**
153
+ * Thrown when `Ajax.get` or `Ajax.post` receives a non-20X response code.
154
+ * Contains the XMLHttpRequest that resulted in that respons
155
+ */
156
+ case class AjaxException (xhr : dom.XMLHttpRequest ) extends Exception
157
+ /**
158
+ * Wraps an XMLHttpRequest to provide an easy one-line way of making
159
+ * an Ajax call, returning a Future.
160
+ */
161
+ object Ajax {
162
+ def get (url : String ,
163
+ data : String = " " ,
164
+ timeout : Int = 0 ,
165
+ headers : Seq [(String , String )] = Nil ,
166
+ withCredentials : Boolean = false ) = {
167
+ apply(" GET" , url, data, timeout, headers, withCredentials)
168
+ }
169
+ def post (url : String ,
170
+ data : String = " " ,
171
+ timeout : Int = 0 ,
172
+ headers : Seq [(String , String )] = Nil ,
173
+ withCredentials : Boolean = false ) = {
174
+ apply(" POST" , url, data, timeout, headers, withCredentials)
175
+ }
176
+ def apply (method : String ,
177
+ url : String ,
178
+ data : js.String ,
179
+ timeout : Int ,
180
+ headers : Seq [(String , String )],
181
+ withCredentials : Boolean ): Future [dom.XMLHttpRequest ] = {
182
+ val req = new dom.XMLHttpRequest ()
183
+ val promise = Promise [dom.XMLHttpRequest ]
184
+ req.withCredentials = withCredentials
185
+
186
+ req.onreadystatechange = {(e : dom.Event ) =>
187
+ if (req.readyState.toInt == 4 ){
188
+ if (200 <= req.status && req.status < 300 )
189
+ promise.success(req)
190
+ else
191
+ promise.failure(AjaxException (req))
192
+ }
193
+ }
194
+ req.open(method, url)
195
+ headers.foreach(x => req.setRequestHeader(x._1, x._2))
196
+ req.send(data)
197
+ promise.future
198
+ }
199
+ }
0 commit comments