Consuming Web API using JavaScript and XMLHttpRequest method
Using JavaScript with remote services by calling REST, JSON, WCF or other web service will decrease data round trips and will allow to create reach web interfaces.
For demo I will use Visual Studio 2012 and MVC4. Client call will be hosted in MVC4 page and service will be provided by WebAPI which is also based on MVC4.
Lets first see how it works in one server environment, more complex scenario will be in next posts.
Start Visual Studio 2012 and create a web site using ASP.NET MVC4 Web Application template.
Then choose Basic template without creating test project.
Create HomeController and corresponding View which will response to root address
I want to skip details about creating controllers and views, you can find a lot of samples and blog posts about it.
On next step I will create another controller which will response to JavaScript calls. To create WebAPI page right click on Controllers folder and click on Add / Web API Controller class.
In new window just edit ValuesController1 by removing trailing 1.
Controller with default methods will be created and that is enough for demo. To confirm and check what is created just build project and run it. Add /api/values which is Web API address by default and confirm response from the server.
The only thing we need is to create a script which will call this web service and show results.
Modify Index view and add to it script block, button and div which will contain the response.
<div><br> <div id="response"> </div><br> <input type="button" value="Call Web API" onclick="javascript:CallWebAPI();" /><br> </div><br> <script type="text/javascript"><br> function CallWebAPI()<br> {<br> var responseContainer = document.getElementById('response');<br> var request = new XMLHttpRequest();<br> request.open("get", "/api/values", false);<br> request.send(); response.innerHTML = request.responseText;<br> }<br> </script>
So as a result you will see injected JSON response. You can manipulate and request response to be in XMLor JSON format.
In the next post I will show how to make cross site requests and what kind of difficulties can occur.
Happy coding!
Comments
- Anonymous
November 23, 2012
Interesting Finds: November 24, 2012