Skip to content

Commit ea8136b

Browse files
author
Li Haoyi
committed
Added a wrapper making XMLHttpRequests much less painful; as time goes on eventually we'll have a similar wrapper for Websockets and other such APIs
1 parent 37a4697 commit ea8136b

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

src/main/scala/org/scalajs/dom/extensions/Extensions.scala

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,3 +147,53 @@ object KeyCode {
147147
val y = 89
148148
val z = 90
149149
}
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

Comments
 (0)