code_junkie

consume a asp.net web service that returns json from an stand alone html page

Nov 13th, 2011
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. <asp:ScriptManager ID="ScriptManager" runat="server">
  2. <Services>
  3. <asp:ServiceReference Path="~MyService.asmx" />
  4. </Services>
  5. </asp:ScriptManager>
  6.  
  7. $.ajax({
  8. type: "POST",
  9. url: "~/MyService.asmx/MyMethod",
  10. data: "{parameterName:'" aStringArgument + "'}",
  11. contentType: "application/json; charset=utf-8",
  12. dataType: "json",
  13. success: function(msg) {
  14. var data = msg.d
  15. // Now var is an object with properties just like your object
  16. }
  17. });
  18.  
  19. [WebMethod]
  20. [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
  21. public String Foo(String p1, String p2)
  22. {
  23. return "Hello World";
  24. }
  25.  
  26. var httpobj = getXmlHttpRequestObject();
  27. //Gets the browser specific XmlHttpRequest Object
  28. function getXmlHttpRequestObject()
  29. {
  30. if (window.XMLHttpRequest)
  31. return new XMLHttpRequest();
  32. else if(window.ActiveXObject)
  33. return new ActiveXObject("Microsoft.XMLHTTP");
  34. }
  35.  
  36. CallService()
  37. {
  38. //Set the JSON formatted input params
  39. var param = "{'p1' : 'value1', 'p2' : 'value2'}";
  40. //Send it to webservice
  41. if(httpobj.readyState == 4 || httpobj.readyState == 0)
  42. {
  43. httpobj.open("POST", 'service.asmx/' + 'Foo', true);
  44. //Mark the request as JSON and UTF-8
  45. httpobj.setRequestHeader('Content-Type','application/json; charset=utf-8');
  46. httpobj.onreadystatechange = OnSuccess;
  47. httpobj.send(param);
  48. }
  49. }
  50.  
  51. //Called on successfull webservice calls
  52. OnSuccess()
  53. {
  54. if (httpobj.readyState == 4)
  55. {
  56. //Retrieve the JSON return param
  57. var response = eval("(" + httpobj.responseText + ")");
  58. }
  59. }
Add Comment
Please, Sign In to add comment