Lets start by creating a sample webservice.
- Create a new Web Service application project from Visual Studio
- Click Ok
- For demonstration lets keep the webservice simple. The template automatically create a HelloWorld webmethod.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace TestWebService
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
} - For demonstration lets keep the webservice simple. The template automatically create a HelloWorld webmethod.
- Add a new website to the Project
- Now we need to add the TestWebService reference to our TestWebsite. For this, right click the TestWebsite reference and select Add Service Reference.
- This will bring up the following window, hit the discover button and press OK
<script language="javascript" type="text/javascript">View the default.aspx in browser will bring the following alert window
window.onload = CallWebService();
var xmlHttp;
function CallWebService() {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.open("post", "http://localhost:2700/Service1.asmx/HelloWorld", false);
xmlHttp.onreadystatechange=doUpdate;
xmlHttp.send();
return false;
}
function doUpdate(){
if (xmlHttp.readyState == 4) {
var startTag = "<string xmlns=\"http://tempuri.org/\">";
var endTag = "</string>";
var exch;
var valueStart = 0;
var valueEnd = 0;
valueStart = xmlHttp.responseXML.xml.indexOf(startTag, valueEnd) + startTag.length;
valueEnd = xmlHttp.responseXml.xml.indexOf(endTag, valueEnd + 1);
exch = xmlHttp.responseXML.xml.substring(valueStart, valueEnd);
alert(exch);
}
}
</script>
What we are doing is, registering a method CallWebService() to the window onload event. In this method we are creating an XMLHttp object. This is used for AJAX call. Once we have this object, we will use the Open method for posting the request to the webservice. The false argument makes the call synchronous. If you are looking for asynchronous, the simply pass true. We need to assign a callback method. This method will get executed once the request object got changed. XMLHttp object has a property called ReadyState which can hold the following value0- uninitialized
1- loading
2- loaded
3-interactive
4-complete
We will check if ready state is complete, means our request was successful. Now we need to parse the returned xml string and get the value.
Note: I will update this article and add some more details like passing parameters back and forth. Keep checking :-)
No comments:
Post a Comment