...doesn't seem that hard if you don't have to support Internet Explorer 9. It may be done like so with JavaScript alone:
<!DOCTYPE html>
<html>
<body>
<script context="text/javascript">
var myping=new XMLHttpRequest();
myping.open("GET", "http://opendoor/api/square?number=7", true);
myping.setRequestHeader("Content-type","application/x-www-form-urlencoded");
myping.setRequestHeader("Accept", "application/json; charset=utf-8");
myping.onload = function (data) {
alert(data.currentTarget.response);
console.log(data.currentTarget.response);
}
myping.send();
</script>
</body>
</html>
"What's at opendoor/api/square then?" you ask? It is an ASP.NET MVC Web API controller action which looks like this:
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace OpenDoor.Controllers
{
public class SquareController : ApiController
{
public HttpResponseMessage Get(string number)
{
string answer;
decimal interpretation = 0;
bool isDecimal = decimal.TryParse(number, out interpretation);
if (isDecimal)
{
answer = interpretation + " squared is: " + (interpretation * interpretation);
} else {
answer = "The value provided was not a number.";
}
var response = Request.CreateResponse<string>(HttpStatusCode.OK, answer);
response.Headers.Add("Access-Control-Allow-Origin","*");
return response;
}
}
}
The following links helped me figure this out and also offered some insights as to how to polyfill older versions of IE.
No comments:
Post a Comment