1

Please help me to solve the following.

There is the client side code to get JSON data from my server:

<input type="button" id="btn" value="btn" />
<script type="text/javascript">
  $('#btn').click(function () {
    $.ajax({
      type: "POST",
      contentType: "application/json; charset=utf-8",
      data: "{'em':'1'}",
      url: "http://myserver/default.aspx/GetInfo",
      dataType: "json",
      success: function (result) {
        $.each(result, function (i, field) {
          alert(field);
        });
      }
    });
  });
</script>

And there is the aspx page on my server with the code:

[System.Web.Services.WebMethod]
public static string GetInfo(string em)
{
  return "{\"a\":\"" + em + "\"}";
}

The task is to create the web method on my aspx page placed on my server for the client to get JSON data to him. When I test it locally it works but when I call web method from the server it doesn't. I know that I should change client code to work with cross-domains but how i should do it when I have web method on server side?

sancoma
  • 11
  • 2
  • The request is restricted by the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy), which can only be relaxed when both the server [and browser](http://caniuse.com/#feat=cors) support [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) (note: [jQuery doesn't support `XDomainRequest` on its own](http://stackoverflow.com/q/11487216)). And, official support for CORS within ASP.NET is primarily [only for Web API](http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api), and that's a recent addition (VS 2013). – Jonathan Lonowski Aug 08 '13 at 07:55
  • I thought that I should use jsonp instead but how I can apply it to webmethod. – sancoma Aug 08 '13 at 08:04
  • Well, you can't `POST` with [JSONP](http://en.wikipedia.org/wiki/JSONP). It can make cross-origin requests because it uses a ` – Jonathan Lonowski Aug 08 '13 at 08:06
  • So what is the way to solve the issue? Maybe I should not use webmethod and use page call instead? – sancoma Aug 08 '13 at 08:08
  • And what about using JSONP with parameters and GET? – sancoma Aug 08 '13 at 09:42

0 Answers0