Reputation: 7824
I've developed a web service in asp.net and am able to test it from an in-project aspx page and can readily display the information that was returned in JSON format.
I now need to consume the web service from a stand-alone html page.
Does someone have experience with this? I'm puzzled by the part that would replace this
<asp:ScriptManager ID="ScriptManager" runat="server">
<Services>
<asp:ServiceReference Path="~\MyService.asmx" />
</Services>
</asp:ScriptManager>
If this is not possible with straight html and javascript, can someone show me a stand-alone php page that would do it?
Upvotes: 2
Views: 2339
Reputation: 315
If you do not want to use the ScriptManager (which adds over 100k of JS to your page), you can use this method to use jQuery to connect to your web services.
Upvotes: 0
Reputation: 950
You can use Javascript to access your webservice.
For example - if you have a json webservice defined like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public String Foo(String p1, String p2)
{
return "Hello World";
}
you could call it as follow:
var httpobj = getXmlHttpRequestObject();
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject()
{
if (window.XMLHttpRequest)
return new XMLHttpRequest();
else if(window.ActiveXObject)
return new ActiveXObject("Microsoft.XMLHTTP");
}
CallService()
{
//Set the JSON formatted input params
var param = "{'p1' : 'value1', 'p2' : 'value2'}";
//Send it to webservice
if(httpobj.readyState == 4 || httpobj.readyState == 0)
{
httpobj.open("POST", 'service.asmx/' + 'Foo', true);
//Mark the request as JSON and UTF-8
httpobj.setRequestHeader('Content-Type','application/json; charset=utf-8');
httpobj.onreadystatechange = OnSuccess;
httpobj.send(param);
}
}
//Called on successfull webservice calls
OnSuccess()
{
if (httpobj.readyState == 4)
{
//Retrieve the JSON return param
var response = eval("(" + httpobj.responseText + ")");
}
}
Upvotes: 0
Reputation: 28499
See this link:
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
Use JQuery
www.jquery.org
Essentially, you make your Web Service script callable, just an attribute in your Web Service definition and you do:
$.ajax({
type: "POST",
url: "~/MyService.asmx/MyMethod",
data: "{parameterName:'" aStringArgument + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var data = msg.d
// Now var is an object with properties just like your object
}
});
Upvotes: 5