Consumes an asp.net web service that returns json from a separate html page

I have developed a web service in asp.net and can inspect it in an aspx page in the project and easily display the information that was returned in JSON format.

Now I need to use the web service in a separate html page.

Does anyone have any experience? I'm puzzled by the part that will 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 separate php page that would do this?

+1


source to share


4 answers


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 the web service definition, and 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
    }
  });

      

+4


source


Use JQUery.



+1


source


You can use Javascript to access your web service.

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 can call it like this:

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 + ")");
   }
}

      

0


source


If you don't want to use the ScriptManager (which adds over 100k JS to your page), you can use this method to use jQuery to connect to your web services .

0


source







All Articles